In Rails, it’s quick and easy to create an RSS feed for anything you could imagine. Recall that RSS feeds are just XML documents that follow a specific format. In addition, Rails makes it easy to use code in and generate XML, the same way it’s easy to use code in and generate HTML.
So how do you do it?
First, add the code in the appropriate controller to grab whatever items you want in your RSS:
def rss
@posts = Posts.find(:all, :limit => 10, :order => "created_on DESC")
end
This code, appropriate for a blog, will fetch the most recent ten posts and dump them in posts.
Because RSS feeds are XML, you need to make sure there’s no layout associated with this action–if there is, Rails will start generating HTML, and that will mess up your XML format. To do that, add this code to your controller:
layout "mylayout", :except => :rss
This ensures that the layout you use won’t apply to your rss action.
Finally, create the view file for the rss action. In this case, your view is going to be an XML document. This file is going to be called rss.rxml, and goes in your views/posts folder. You can use the template from here for an RSS 2.0 compliant feed:
xml.instruct! :xml, :version=>"1.0"
xml.rss(:version=>"2.0"){
xml.channel{
xml.title("Your Blog's Title")
xml.link("http://www.yoursite.tld/")
xml.description("What your site is all about.")
xml.language('en-us')
for post in @posts
xml.item do
xml.title(post.title)
xml.description(post.html_content)
xml.author("Your Name Here")
xml.pubDate(post.created_on.strftime("%a, %d %b %Y %H:%M:%S %z"))
xml.link(post.link)
xml.guid(post.link)
end
end
}
}
Notice that it has a for-loop in it–Rails code! The link will specify what link the title has if you’re viewing it in a reader that honours links (Firefox doesn’t show links for the raw feed, but IE7 does). Also, you need a GUID–a unique identifier for every element in your collection. Links are usually a good unique item.
Also, notice the first line of the XML feed–it generates an XML opening-tag. If you try to view the feed in IE7, this tag will cause an error, because IE7 doesn’t honour the RSS 2.0 format. (To “fix” it, simply delete the xml.instruct line–but that makes your feed non-standards-compliant!)
Finally, if you want browsers to pick up the feed automatically when a user browses to your site–Firefox displays a small feed icon in the address bar–add this code into the head tag of your layout:
<%= auto_discovery_link_tag(:rss, :controller => "ControllerWithFeedAction", :action => 'feed') %>
And that’s it! Rails will generate the feed perfectly, and everything will (hopefully) work without a hitch.