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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With