Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrict specific fields in the response of rails controller

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.

like image 921
Sarvesh Avatar asked Aug 02 '11 21:08

Sarvesh


2 Answers

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.

like image 61
Maurício Linhares Avatar answered Sep 23 '22 10:09

Maurício Linhares


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.

like image 44
Dylan Markow Avatar answered Sep 25 '22 10:09

Dylan Markow