Rails中的无表格模型JSON序列化
我有无表格模型(就像在#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)
我知道这不是直截了当但是怎么样:
render :json => @my_model.attributes.slice(:attr1, :attr2)
您还需要将属性方法定义为:
def attributes {:attr1 => self.attr1.....} end
感谢bender的评论。
我相信这是因为Object :: as_json在内部调用(看看这个: http ://apidock.com/rails/Object/as_json),它没有像:only或:except之类的选项,所以你可以覆盖方法to_hash in你的class级,例如:
def to_hash {:attr1 => self.attr1, :attr2 => self.attr2} end
和to_json将完全按照你的意愿行事。
当然,另一个选择是覆盖方法to_json …
如文档所示,您可以将初始方法(包括AM序列化模块)与Erez的方法混合使用。
class MyModel include ActiveModel::Serialization::JSON .... def attributes {:attr1 => self.attr1.....} end ... end