Read more

Create a valid RSS feed in Rails

Henning Koch
September 14, 2010Software engineer at makandra GmbH

This will show you how to create a RSS feed that the Feed Validator Show archive.org snapshot considers valid.

Illustration online protection

Rails professionals since 2007

Our laser focus on a single technology has made us a leader in this space. Need help?

  • We build a solid first version of your product
  • We train your development team
  • We rescue your project in trouble
Read more Show archive.org snapshot

Note that RSS is a poorly specified format. Consider using the Atom builder Show archive.org snapshot to make an Atom feed instead. Write a note here if you do.

  1. Controller

Create a FeedsController to host the RSS feed. Such a controller is also useful to host other data feeds that tend to gather over the lifetime of an application, e.g. sitemap.xml.:

class FeedsController < ApplicationController

  layout false

  def rss
    @notes = Note.all(:order => 'created_at DESC', :limit => 50)
  end

end
  1. Routes

Connect a route to the feed in config/routes.rb:

map.feed 'feed.rss', :controller => 'feeds', :action => 'rss', :format => 'rss'
  1. View

Create a view in views/feeds/rss.rss.builder [sic]. Prefer the builder to using Haml because XML schemas can be strict about whitespace, whereas Haml is not.

xml.instruct!
xml.rss :version => '2.0', 'xmlns:atom' => 'http://www.w3.org/2005/Atom' do

  xml.channel do
    xml.title 'Feed title'
    xml.description 'Feed description'
    xml.link root_url
    xml.language 'en'
    xml.tag! 'atom:link', :rel => 'self', :type => 'application/rss+xml', :href => feed_url

    for note in @notes
      xml.item do
        xml.title note.title
        xml.link note_url(note)
        xml.pubDate(note.created_at.rfc2822)
        xml.guid note.guid
        xml.description(h(note.body))
      end
    end

  end

end
  1. Layout

Add a link to the <head> of your layout so the feed can be auto-discovered by browsers:

%html
  %head
    %link{ :href => feed_url, :rel => "alternate", :type => "application/rss+xml", :title => "RSS feed" }
Henning Koch
September 14, 2010Software engineer at makandra GmbH
Posted by Henning Koch to makandra dev (2010-09-14 10:28)