0

I'm building an XML feed for my application and am wondering what the best way to implement it would be.

I have an Item class, with a field "related_item," which right now contains ids to related items in an array)

For instance, I could have the following item:

id: 3  
name: an item  
related_items: [67, 94, ...]

and would like to get the following xml when I access mysite.com/items/3.xml:

<item>
  <id>3</id> <name>An item</name>
  <related-items> 
    <related-item> <id>67</id> <name>A related items</name> </related-item>
    <related-item> <id>94</id> <name>Another related items</name> </related-item>
    <related-item> ... </related-item> 
  </related-items> 
</item>

What's a good way to accomplish that (this is just an example, I will actually have many more fields and would like to avoid rewriting as much as I can)? Thanks

0

3 Answers 3

1

See great Railscast here.

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

3 Comments

you even have an example on the first page, without watching anything
Something I don't understand: let's say I want to have an xml for a user, with its associated items. How can I reuse the code I wrote in items/show.xml.builder in users/show.xml.builder?
Or, if I want a feed with search results, and want to use several Items in the feed, how do I avoid duplicating my code?
1

In order to avoid duplicating code, I preferred using serialization as opposed to creating a builder view. I used a little trick in order to avoid "stack too deep" problems. Here is how it look:

class Item

def to_xml(options={})
      if options[:short]
        options.merge!(:only => [:id, :name])
      else
        options.merge!(:only => [:id, :name], :include => {:related_items => {:short => true}})
      end
      super(options)
end

That way I can reuse my to_xml in other places. For instance, in my user controller I can do:

format.xml {render :xml => @user.to_xml(:include => :user_items)}

It's the best way to do it I could find.

2 Comments

I didn't realize that's what you expected. Good catch, +1
thanks!... It was hard to formulate the question precisely. Sorry for the confusion.
0

not neccesary RSS feed is needed, but simple XML builder.. some links:

http://danengle.us/2009/05/generating-custom-xml-for-your-rails-app/

http://prograstinator.blogspot.com/2010/02/how-to-use-xml-builder-templates-in.html

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.