14

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.

Dylan Markow
  • 123,080
  • 26
  • 284
  • 201
Sarvesh
  • 1,152
  • 2
  • 11
  • 25

4 Answers4

40

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.

Maurício Linhares
  • 39,901
  • 14
  • 121
  • 158
13

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.

Dylan Markow
  • 123,080
  • 26
  • 284
  • 201
2

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.

Community
  • 1
  • 1
jpemberthy
  • 7,473
  • 8
  • 44
  • 52
-6

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

Jon
  • 555
  • 5
  • 5