问题
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.
回答1:
Doing it like this:
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
You can find more info about this at the serialization documentation.
回答2:
You can use a select clause on your Video.all query, specifying the fields you want to include.
@videos = Video.select("id, name, title").all
Also, you shouldn't need to call to_a on your query.
回答3:
You can define your own .to_xml method inside video.rb,
e.g:
class Video < ActiveRecord::Base
def to_xml(opts={})
opts.merge!(:only => [:id, :title])
super(opts)
end
end
And then call respond_with(@videos) in you controller.
See this similar question.
回答4:
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
def index
@titles = Video.pluck(:title)
respond_to do |format|
format.xml { render :xml => @titles }
format.json { render :json => @titles }
end
end
: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 :
@videos_ary = Video.pluck(:id, :title)
response = @videos_ary.map {|va| { id: va[0], title: va[1] }}
if you dont want to get your SQL pencil out, this is pretty good
来源:https://stackoverflow.com/questions/6919147/restrict-specific-fields-in-the-response-of-rails-controller