15

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.

4 Answers 4

41

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

As well, I dont believe you need the :all on this query
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.

Comments

-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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.