开发者

Filter json render in Rails

开发者 https://www.devze.com 2023-02-18 06:16 出处:网络
What is the best way if i would like to only retur开发者_StackOverflow社区n :id and :name fields in JSON

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

0

精彩评论

暂无评论...
验证码 换一张
取 消