Thursday, November 26, 2015

How to create a valid RSS feed in Rails

6:28 PM Posted by Unknown 1 comment

Step 1

Create a new method in the posts controller.
app/controllers/blog_articles_controller.rb
class PostsController < ApplicationController

  ...

  def feed
    @posts = Post.all.order('created_at DESC').limit(20)
    respond_to do |format|
      format.rss { render :layout => false }
    end
  end

end

Step 2

Add a "view" for the feed.

Create the file
app/views/posts/feed.rss.builder
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 post in @posts
      xml.item do
        xml.title post.title
        xml.link post_url(post)
        xml.pubDate(post.created_at.rfc2822)
        xml.guid post_url(post)
        xml.description post.description
      end
    end
 
  end
 
end

Step 3

Add a route to /feed in the router file.

Edit
config/routes.rb

Add
get 'feed' => 'posts#feed'

Step 4

Add the following entry in the head section of your site template.

Edit
views/layouts/application.html.erb

Add a line like
<link href="https://www.your_website.com/feed?format=rss" rel="alternate" title="Your website RSS Feed" type="application/rss+xml"></link>
Then you can check Feed Validator for Atom and RSS here:  http://feedvalidator.org

1 comment:

  1. After reading this blog i very strong in this topics and this blog really helpful to all... explanation are very clear so very easy to understand... thanks a lot for sharing this blog
    Ruby on Rails Online Course India

    ReplyDelete