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开发者_StackOverflow中文版 I can)? Thanks
See great Railscast here.
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.
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
精彩评论