【问题标题】:Adding further attributes to a ActiveRecord serialization?向 ActiveRecord 序列化添加更多属性?
【发布时间】:2010-10-15 13:18:02
【问题描述】:

我的 json 序列化工作正常

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

但我还想在它被设置回客户端之前向 json 添加更多数据。主要是auth_token。

疯狂地用谷歌搜索,但我找不到序列化将采取什么选项来允许我将其他数据附加/合并到 JSON 中。

希望找到类似的东西......

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

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 对不起,我想我可以解释得更好一点。我要附加的额外数据 (form_aithenticity_token) 不是 ActiveRecord 模型的函数。还要注意的是,调用 #to_json 会忽略根节点。 {model_name: {...}}
    【解决方案2】:

    对于它的价值,在最近的 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 是您想要设置值的任何内容。

    吉米

    【讨论】:

      【解决方案3】:

      破解它并继续前进......

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

      【讨论】:

        猜你喜欢
        • 2021-03-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-28
        • 1970-01-01
        相关资源
        最近更新 更多