Filter json render in Rails
What is the best way if i would like to only retur开发者_StackOverflow社区n :id and :name fields in JSON
So far i have:
format.json { render :json => @contacts.map(&:attributes) , :only => ["id"]}
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)
Thanks!
Rails 3 supports following filter options. as simple as is
respond_to do |format|
format.json { render json: @contacts, :only => [:id, :name] }
end
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
See: http://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html#method-i-as_json
精彩评论