In this article we will show you how to add an Atom feed to your application. Atom feeds are used in many different ways. Users use your atom feeds in feed readers to browse your content. Search engines use your atom feed to help discover additional information about your site.
The first thing we need to do is add some code to our controller to actually pull the data from our database in the proper order. Inside your index method, add the following code, making changes as necessary for your situation:
@posts = Post.order("created_at DESC")
This will pull all of our posts, ordering them by newest first. Next, we will need to create a new file called an atom feed builder that will serve as a template for the model in question. Create a file called index.atom.builder under app/views/<model> where model is the model you wish to use the atom feed for. Next, add the following code to your atom feed:
xml.feed do |feed| feed.title = "My Blog Posts" end
The feed.title specifies the title of our atom feed. Next, we will need to add some code that tells users when the atom feed was last updated. Add the following code after feed.title:
This will tell users when we last updated our site. Next, we will need to loop through each of our models and render the title, content, url, and author. Add the following code below the feed.updated line:
@posts.each do |post| feed.entry post do |entry| entry.title post.title entry.content post.body entry.url post_path(post) entry.author do |author| author.name "Rich" end end # end feed.entry end # end @posts.each
The code above will generate a basic atom feed. If you go to the atom feed on your site, (in this example: http://localhost:3000/posts.atom) you will be able to either subscribe to your feed or download it depending on browser support. We have one final thing we need to add. Open your layouts/application.html.erb view and add the following code in between the html head open/close tags:
<%= content_for :head %>
Next, open up the posts/index.html.erb view and add the following code:
<%= content_for :head, auto_discovery_link_tag(:atom, posts_url(format: "atom")) %>
That's it! You are all set. When you visit http://localhost:3000/posts you should be able to view the source and see that an autodiscovery link has been added for your atom feed.