Ruby on rails Rails属性存取器&x27;在将对象数组转换为JSON时,s将消失
我有一个订单模型:Ruby on rails Rails属性存取器&x27;在将对象数组转换为JSON时,s将消失,ruby-on-rails,ruby,Ruby On Rails,Ruby,我有一个订单模型: class Order < ActiveRecord::Base attr_accessor :total_cost end 类顺序
class Order < ActiveRecord::Base
attr_accessor :total_cost
end
类顺序
这是我获取订单的控制器:
class OrdersController < ApplicationController
before_action :authenticate_user!
def fetch_orders
data = Order.all
data_with_appended_fields = append_calculated_fields(data)
render json: { success: true, data: data_with_appended_fields}
end
private
def append_calculated_fields(data)
new_data = data.each do |order|
order.total_cost = 10
end
new_data
end
end
class OrdersController
在我的方法中,当我打印新数据时,append\u computed\u fields
。在json中,我添加的attr\u accessor
字段不在json中
当我打印订单.总成本时,设置后,它显示值10
我是不是走错了路
我试图将计算字段添加到对象的数组中,并返回带有计算值的数据
能够将
新的\u数据返回到\u json(:methods=>[:total\u cost])
并获得我所需的输出。如果您使用的是Rails 5+您应该使用而不是attr\u访问器<代码>属性:total_cost,:integer
。ActiveModel::Serializers::JSON不会“拾取”ActiveRecord模型中使用attr_访问器定义的属性。最好在模型或服务中使用此类方法。控制器是为请求而设计的这是否回答了您的问题?可能重复的