I decided to do a follow up on Part 3 of my series on building a blog in Rails 7 so that I could dive a bit deeper on how to more effectively setup your blog for SEO as it's crucial to focus not only on content but also on SEO. By integrating SEO metadata into your Rails 7 blog application, you can improve your blog's search engine visibility and help users discover your content. In this blog post, I'll walk you through adding title tags, meta descriptions, Open Graph tags, and Twitter Card tags to your Rails 7 blog.
Step 1: Create a layout helper
To avoid repeating the metadata code for each view, create a helper method that sets default values for your metadata and allows you to overwrite them for specific views. In app/helpers/application_helper.rb, add the following method:
module ApplicationHelper def page_title(title = nil) base_title = "Your Blog Name" title.present? ? "#{title} | #{base_title}" : base_title end end
Replace "Your Blog Name" with your actual blog name. This method sets the base title and appends the given title, separated by a pipe symbol.
Step 2: Set up title tags and meta descriptions
In your application layout file (app/views/layouts/application.html.erb), add the title tag and meta description within the <head> section:
<head> <title><%= page_title(yield(:title)) %></title> <meta name="description" content="<%= yield(:description) %>"> <!-- Other tags... --> </head>
Step 3: Provide page-specific metadata
In each blog post view (e.g., show.html.erb), set the page-specific metadata using the content_for helper:
<% content_for :title, @post.title %> <% content_for :description, truncate(strip_tags(@post.content), length: 155, separator: ' ', omission: '...') %>
Step 4: Add Open Graph and Twitter Card tags
Add Open Graph and Twitter Card tags to the <head> section of the application layout file (app/views/layouts/application.html.erb):
<head> <!-- Title and meta description tags... --> <meta property="og:title" content="<%= page_title(yield(:title)) %>"> <meta property="og:description" content="<%= yield(:description) %>"> <meta property="og:type" content="article"> <meta property="og:url" content="<%= request.original_url %>"> <meta property="og:image" content="<%= yield(:image) %>"> <meta property="og:site_name" content="Your Blog Name"> <meta name="twitter:card" content="summary_large_image"> <meta name="twitter:title" content="<%= page_title(yield(:title)) %>"> <meta name="twitter:description" content="<%= yield(:description) %>"> <meta name="twitter:image" content="<%= yield(:image) %>"> <!-- Other tags... --> </head>
Replace "Your Blog Name" with your actual blog name.
Step 5: Set page-specific Open Graph and Twitter Card images
In each blog post view (e.g., show.html.erb), set the page-specific Open Graph and Twitter Card image URLs:
<% content_for :image, url_for(@post.featured_image) if @post.featured_image.attached? %>
That's it, happy blogging!