且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Rails中过滤json渲染

更新时间:2023-11-10 23:08:22

您可以将:methods传递给to_json/as_json

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

请参阅: http://api.rubyonrails.org/classes/ActiveModel /Serializers/JSON.html#method-i-as_json