在Rails中过滤json渲染

如果我只想返回的最佳方式是什么:id和:JSON中的name字段

到目前为止,我有:

format.json { render :json => @contacts.map(&:attributes) , :only => ["id"]} 

但是“name”属性在:only部分中不起作用,因为它不是数据库中的列(它在模型中定义为firstname + lastname)

谢谢!

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

 format.json do render :json => @contacts.map { |contact| contact.as_json(:only => :id, :methods => :name) } end 

或者,您可以手动构建哈希

 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

Rails 3支持以下filter选项。 就这么简单

 respond_to do |format| format.json { render json: @contacts, :only => [:id, :name] } end