How to add a RSS feed to a rails blog
RSS Feeds are publicly accessible URLs of websites that can be consumed by other software in order to utilize the content of a site. If you write posts on your own blog like I do and then want to crosspost your posts to other sites like dev.to, a RSS feed might be helpful in doing so.
The RSS feed of my blog is available at /feed. It gets generated dynamically so it always includes my latest posts.
How to add a RSS feed with Rails
The way I implemented this RSS feed is very similar to the way I implemented
my Sitemap.xml first lets add a route to our
get 'feed', to: 'home#feed', format: 'xml', as: :feed
As you can see, it expects to find a controller
home with an action
feed, so either create this controller too yourself or point
to a different one in your application. The action itself is empty:
class HomeController < ApplicationController def feed end end
The last thing we need is the view file
views/home/feed.xml.builder which generates the xml code. It iterates through published posts,
paginates them and then renders XML for each of them.
xml.instruct! :xml, version: "1.0" xml.rss :version => "2.0" do xml.channel do xml.title "WebDevChallenges" xml.description "A blog about the lessons learned as a Web Developer" xml.link root_url Post.published.order('created_at DESC').page(1).each do |post| xml.item do xml.title post.title xml.description post.html_content xml.pubDate post.created_at.to_s(:rfc822) xml.link show_post_url(post.slug) xml.guid show_post_url(post.slug) end end end end
As mentioned earlier, some sites like dev.to offer the possibility to enter your own RSS feed which then gets fetched regularly. If it detects a new post, it will land in your dashboard as a draft which you then can use to easily release your post there aswell which is exactly what I do.
Important to note here is that posting your content on multiple platforms might be negative in terms of SEO if google cannot find out which of the websites is the original creator of the content. dev.to offers you the option to set a canonical URL so it won’t affect your SEO negatively. The canonical URL gets set automatically if import your posts via RSS.
Hope that helped :)