限制rails控制器响应中的特定字段

我有一个控制器动作

def index @videos = Video.all.to_a respond_to do |format| format.xml { render :xml => @videos } format.json { render :json => @videos } end end 

video具有属性nametitle

我希望返回xml只包含title

如何从响应中限制它。

这样做:

 def index @videos = Video.all respond_to do |format| format.xml { render :xml => @videos.to_xml( :only => [:title] ) } format.json { render :json => @videos.to_json( :only => [:title] ) } end end 

您可以在序列化文档中找到有关此内容的更多信息。

您可以在Video.all查询中使用select子句,指定要包含的字段。

 @videos = Video.select("id, name, title").all 

此外,您不需要在查询中调用to_a

您可以在video.rb定义自己的.to_xml方法,

例如:

 class Video < ActiveRecord::Base def to_xml(opts={}) opts.merge!(:only => [:id, :title]) super(opts) end end 

然后在你的控制器中调用respond_with(@videos)

看到这个类似的问题 。

一个快速的方法是使用:pluck ,如果你只是返回一个标题数组(我猜不是:id),那么这将非常快

 def index @titles = Video.pluck(:title) respond_to do |format| format.xml { render :xml => @titles } format.json { render :json => @titles } end end 

:pluck将比任何其他选项更快,因为它返回一个只包含所请求数据的数组。 它不会为每个数据库行实例化整个ActiveRecord对象。 因为它的ruby,这些实例化大部分时间都是如此。 你也可以这样做:

 @videos_ary = Video.pluck(:id, :title) response = @videos_ary.map {|va| { id: va[0], title: va[1] }} 

如果你不想让你的SQL铅笔出来,这是非常好的