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

时间:2011-08-02 21:52:55

标签: ruby-on-rails controller

我有像

这样的控制器动作
def index
  @videos =  Video.all.to_a

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

视频包含nametitle属性。

我希望return xml仅包含title

如何从响应中限制它。

4 个答案:

答案 0 :(得分:29)

这样做:

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找到更多相关信息。

答案 1 :(得分:11)

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

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

此外,您不需要在查询中致电to_a

答案 2 :(得分: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

答案 3 :(得分:-3)

快速的方法是使用: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对象。因为它的红宝石,这些实例化大部分时间都是如此。你也可以这样做:

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

如果你不想把你的SQL铅笔拿出来,那就非常好了

相关问题