繁体   English   中英

在Rails中过滤json渲染

[英]Filter json render in Rails

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

到目前为止,我有:

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

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

谢谢!

Rails 3支持以下过滤器选项。 就这么简单

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

您可以将: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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM