【问题标题】:Tableless model JSON serialization in RailsRails 中的无表模型 JSON 序列化
【发布时间】:2012-07-07 10:33:19
【问题描述】:

我有无表模型(如 #219 railscast 中所示):

class MyModel
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  attr_accessor :attr1, :attr2, :attr3, :attr4

  private
    def initialize(attr1 = nil)
      self.attr1 = attr1
    end

    def persisted?
      false
    end
end

然后我尝试在控制器中渲染 JSON:

@my_model = MyModel.new
render json: @my_model.to_json(only: [:attr1, :attr2])

但它使用模型的所有属性呈现 JSON。

我已经尝试添加

include ActiveModel::Serialization

但它并没有改变呈现的 JSON。

如何仅使用无表模型的必要属性呈现 JSON?

我正在使用 Rails 3.2.3

更新

谢谢,伙计们。看来你几乎是对的。我结合了您的解决方案并得到了这个:

型号:

include ActiveModel::Serialization

...

def to_hash
  {
    attr1: self.attr1,
    attr2: self.attr2,
    ...
  }
end

控制器:

render json: @my_model.to_hash.to_json(only: [:attr1, :attr2])

我真的不知道该接受谁的答案。

更新 2

突然出现了新的陌生感。属性之一是哈希数组。是这样的:

attr1: [[{name: "name", image: "image"}, {name: "name", image: "image"}],
        [{name: "name", image: "image"}, {name: "name", image: "image"}]]

但现在它失去了所有内容,看起来像这样:

attr1: [[{}, {}], [{}, {}]]

也许有人知道如何解决它?

更新 3 :)

Erez Rabih 的回答有所帮助。使用slice 而不是to_json 解决了这个问题。所以,最终的解决方案是:

render json: @my_model.to_hash.slice(:attr1, :attr2)

【问题讨论】:

    标签: ruby-on-rails json


    【解决方案1】:

    我知道这不是直截了当,但是怎么样:

    render :json => @my_model.attributes.slice(:attr1, :attr2)
    

    您还需要将属性方法定义为:

    def attributes
       {:attr1 => self.attr1.....}
    end
    

    感谢您的评论。

    【讨论】:

      【解决方案2】:

      我相信这是因为 Object::as_json 在内部调用(看这个:http://apidock.com/rails/Object/as_json),它没有像 :only 或 :except 这样的选项,所以你可以在你的类中覆盖方法 to_hash,例如:

      def to_hash
        {:attr1 => self.attr1, :attr2 => self.attr2}
      end
      

      并且 to_json 将完全按照您的意愿行事。

      当然,另一种选择是覆盖方法 to_json ...

      【讨论】:

      • 我遇到了和 OP 一样的问题,这对我来说似乎没有任何改变......
      【解决方案3】:

      您可以按照documentation 的建议将您的初始方法(包括 AM 序列化模块)与 Erez 的方法混合使用。

      class MyModel
          include ActiveModel::Serialization::JSON
          ....
          def attributes
             {:attr1 => self.attr1.....}
          end
          ...
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-13
        • 1970-01-01
        • 2011-09-06
        • 2017-03-03
        • 2023-03-20
        • 2011-05-26
        • 1970-01-01
        • 2016-11-21
        相关资源
        最近更新 更多