Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter json render in Rails

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!

like image 302
montrealmike Avatar asked Mar 22 '11 17:03

montrealmike


2 Answers

Rails 3 supports following filter options. as simple as is

respond_to do |format|
  format.json { render json: @contacts, :only => [:id, :name] }
end  
like image 159
elias Avatar answered Nov 10 '22 11:11

elias


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

like image 31
lebreeze Avatar answered Nov 10 '22 11:11

lebreeze