2011-08-02 75 views
7

的响应特定的字段我有一个像限制在轨道控制器

def index 
    @videos = Video.all.to_a 

    respond_to do |format| 
    format.xml { render :xml => @videos } 
    format.json { render :json => @videos } 
    end 
end 

视频控制器操作有属性nametitle

我想返回XML只包含title

如何从响应中限制它。

回答

11

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

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

此外,您不应该在您的查询中致电to_a

+2

同时,我不相信你所需要的:所有在此查询 – Jon

24

做这样的:

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 

您可以在the serialization documentation找到更多这方面的信息。

2

您可以定义自己的.to_xml方法内部video.rb

e.g:

class Video < ActiveRecord::Base 

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

end 

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

看到这个similar question

-1

一个快速的方法是使用:采摘,如果你只是返回标题的阵列(我猜没有:ID),那么这将是非常快的

def index 
    @titles = Video.pluck(:title) 

    respond_to do |format| 
    format.xml { render :xml => @titles } 
    format.json { render :json => @titles } 
    end 
end 

:动物内脏将比任何其他选项快得多,因为它仅返回一个仅包含请求数据的数组。它没有为每个数据库行实例化整个ActiveRecord对象。因为它的红宝石,那些实例是大部分时间需要的。你也可以这样做:

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

,如果你不想让你的SQL铅笔出来,这是相当不错的