【问题标题】:Restrict specific fields in the response of rails controller限制 Rails 控制器响应中的特定字段
【发布时间】:2011-08-02 21:52:54
【问题描述】:
我有一个控制器动作,比如
def index
@videos = Video.all.to_a
respond_to do |format|
format.xml { render :xml => @videos }
format.json { render :json => @videos }
end
end
视频具有name 和title 属性。
我希望返回的 xml 仅包含 title。
如何从响应中限制它。
【问题讨论】:
标签:
ruby-on-rails
controller
【解决方案1】:
这样做:
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】:
您可以在 Video.all 查询中使用 select 子句,指定要包含的字段。
@videos = Video.select("id, name, title").all
此外,您不需要在查询时调用 to_a。
【解决方案3】:
您可以在video.rb 中定义自己的.to_xml 方法,
例如:
class Video < ActiveRecord::Base
def to_xml(opts={})
opts.merge!(:only => [:id, :title])
super(opts)
end
end
然后在你的控制器中调用respond_with(@videos)。
看到这个similar question。
【解决方案4】:
一个快速的方法是使用 :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 铅笔,这很好