Sarvesh
Sarvesh

Reputation: 1202

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.

Upvotes: 15

Views: 16561

Answers (4)

Jon
Jon

Reputation: 565

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

Upvotes: -6

jpemberthy
jpemberthy

Reputation: 7533

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.

Upvotes: 2

Maur&#237;cio Linhares
Maur&#237;cio Linhares

Reputation: 40333

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.

Upvotes: 41

Dylan Markow
Dylan Markow

Reputation: 124429

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.

Upvotes: 13

Related Questions