Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails属性存取器&x27;在将对象数组转换为JSON时,s将消失_Ruby On Rails_Ruby - Fatal编程技术网

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_访问器定义的属性。最好在模型或服务中使用此类方法。控制器是为请求而设计的这是否回答了您的问题?可能重复的