限制 Rails 控制器响应中的特定字段
我有一个像 Video 这样的控制器操作
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
。
我如何限制它的响应。
I have a controller action like
def index
@videos = Video.all.to_a
respond_to do |format|
format.xml { render :xml => @videos }
format.json { render :json => @videos }
end
end
Video has attributes name
and title
.
I want the return xml to contain only title
.
How do I restrict it from the response.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这样做:
您可以在序列化文档中找到更多相关信息。
Doing it like this:
You can find more info about this at the serialization documentation.
您可以在
Video.all
查询中使用select
子句,指定要包含的字段。此外,您不需要在查询中调用
to_a
。You can use a
select
clause on yourVideo.all
query, specifying the fields you want to include.Also, you shouldn't need to call
to_a
on your query.您可以在
video.rb
中定义自己的.to_xml
方法,例如:
然后在控制器中调用
respond_with(@videos)
。请参阅此类似问题。
You can define your own
.to_xml
method insidevideo.rb
,e.g:
And then call
respond_with(@videos)
in you controller.See this similar question.
一种快速的方法是使用 :pluck ,如果你只是返回一个标题数组(我猜没有 :id),那么这会非常快
:pluck将比任何其他选项快得多,因为它返回一个仅包含所请求数据的数组。它不会为每个数据库行实例化整个 ActiveRecord 对象。因为它是红宝石,所以这些实例化花费了大部分时间。你也可以这样做:
如果你不想拿出 SQL 铅笔,这很好
a fast way would be to use :pluck, if you are just returning an array of titles (I am guessing no :id) , then this would be very fast
:pluck will be way faster than any of the other options because it returns an array with just the data requested. It doesn't instantiate an entire ActiveRecord Object for each database row. Because its ruby, those instantiations are what take most of the time. You can also do :
if you dont want to get your SQL pencil out, this is pretty good