18

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!

Pavel Chuchuva
  • 22,633
  • 10
  • 99
  • 115
montrealmike
  • 11,433
  • 10
  • 64
  • 86

2 Answers2

35

Rails 3 supports following filter options. as simple as is

respond_to do |format|
  format.json { render json: @contacts, :only => [:id, :name] }
end  
zaqwery
  • 381
  • 3
  • 9
31

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

lebreeze
  • 5,094
  • 26
  • 34
  • We updated our comment at the same time. Now i get: [{"contact":{"name":"Executor From_wizard","id":null}}] but i need [{"name":"Executor From_wizard","id":"1"}] – montrealmike Mar 22 '11 at 18:02
  • Try setting this first `ActiveModel::Base.include_root_in_json = false` – lebreeze Mar 22 '11 at 18:06
  • no way to use the .map(&:attributes) somewhere to only show attributes? Not sure i want to change the default behaviour. Thanks! – montrealmike Mar 22 '11 at 18:18
  • ok found a way that works: render :json => @contacts.map { |contact| {:id => contact.id, :name => contact.name} } Thanks for the help. Please edit your answer with this info, i'll set it as good answer. – montrealmike Mar 22 '11 at 18:22