Ruby on rails 是否向ActiveRecord序列化添加更多属性?

Ruby on rails 是否向ActiveRecord序列化添加更多属性?,ruby-on-rails,ruby,json,serialization,activerecord,Ruby On Rails,Ruby,Json,Serialization,Activerecord,我的json序列化工作正常 render :json => "#{current_object.serialize(:json, :attributes => [:id, :name])} 但我还想在json返回到客户机之前向其添加更多数据。主要是auth_令牌 谷歌搜索得很疯狂,但我找不到serialize将采取什么选项来允许我将其他数据附加/合并到JSON中 希望找到像这样的东西 current_object.serialize(:json, :attriubtes =>

我的json序列化工作正常

render :json => "#{current_object.serialize(:json, :attributes => [:id, :name])}
但我还想在json返回到客户机之前向其添加更多数据。主要是auth_令牌

谷歌搜索得很疯狂,但我找不到serialize将采取什么选项来允许我将其他数据附加/合并到JSON中

希望找到像这样的东西

current_object.serialize(:json, :attriubtes => [:id, name], :magic_option => {:form_authenticity_token => "#{form_authenticity_token}"})

侵入并继续前进

current_object.serialize(:json, :attributes => [:id, :name]).gsub(/\}$/, ", \"form_authenticity_token\": \"#{form_authenticity_token}\"}")

您需要:methods键,该键类似于:attributes,但将包含给定方法的结果。就你而言:

current_object.to_json(
  :attributes => [:id, :name],
  :methods => [:form_authenticity_token]
)

值得一提的是,在最近的一次Rails中,我将您想要的东西如下:

sr = ActiveRecord::Serialization::Serializer.new(your_object, some_serialization_options).serializable_record
sr['extra'] = my_extra_calculation(some_parameters)
format.json { render :json => sr }
如果要序列化的对象是\u对象,则一些\u序列化\u选项是标准的:include、:only等参数,而my\u extra\u计算是设置值所需的任何操作


吉米

对不起,我想我本可以解释得更清楚一点的。我希望附加的额外数据(form_aithentity_token)不是ActiveRecord模型的函数。还需要注意的是,调用#to_json会遗漏根节点。{model_name:{…}