将其他属性添加到ActiveRecord序列化?

时间:2009-03-25 19:56:40

标签: ruby-on-rails ruby json serialization activerecord

我的json序列化工作正常

render :json => "#{current_object.serialize(:json, :attributes => [:id, :name])}

但我还希望在json回到客户端之前将更多数据添加到json。主要是auth_token。

用疯狂的搜索,但我找不到序列化将允许我将其他数据追加/合并到JSON中的选项。

跳起来找到这样的东西......

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

3 个答案:

答案 0 :(得分:4)

你想要:methods键,它的作用类似于:attributes,但是会包含给定方法的结果。在你的情况下:

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

答案 1 :(得分:1)

对于它的价值,在最近的一次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 }

如果your_object是您要序列化的内容,some_serialization_options是您的标准:include,:only等参数,my_extra_calculation是您想要设置值的任何内容。

答案 2 :(得分:0)

将其搞砸并继续......

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