在Rails中过滤json渲染
问题描述:
如果我只想返回JSON中的:id和:name字段,最好的方法是什么
What is the best way if i would like to only return :id and :name fields in JSON
到目前为止,我有:
format.json { render :json => @contacts.map(&:attributes) , :only => ["id"]}
但是"name"属性在:only部分中不起作用,因为它不是数据库中的列(在模型中定义为firstname + lastname)
But the "name" attribute does not work in the :only section, since it is not a column in the database (it is defined in the model as firstname + lastname)
谢谢!
答
您可以将:methods
传递给to_json/as_json
You can pass :methods
to to_json / as_json
format.json do
render :json => @contacts.map { |contact| contact.as_json(:only => :id, :methods => :name) }
end
或者,您也可以手动构建哈希值
Alternatively you can just build up a hash manually
format.json do
render :json => @contacts.map { |contact| {:id => contact.id, :name => contact.name} }
end
请参阅: http://api.rubyonrails.org/classes/ActiveModel /Serializers/JSON.html#method-i-as_json