Reputation: 11641
What is the best way if i would like to only return :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!
Upvotes: 18
Views: 16668
Reputation: 381
Rails 3 supports following filter options. as simple as is
respond_to do |format|
format.json { render json: @contacts, :only => [:id, :name] }
end
Upvotes: 35
Reputation: 5134
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
Upvotes: 31