Adding meta tags in Rails 4 app for each post in Views
In this blog post, we will learn how to add meta-content into our rails 4 app, which will render meta content with respect to each blog post.
We are going to use a fantastic gem called meta-tags by Dmytro Shteflyuk, which not only made it fairly easy to implement but also gives us all the flexibility to customize according to our needs (but that would be out of scope of this post).
Now let’s dive right into the implementation.
I am assuming you already have your rails app running. Let’s add the meta-tags gem to your Gemfile. Then bundle install
.
Create a migration file to add meta fields for your model (in this case I am using my Post model).
You may want to add ‘title’, if you would like to have different title in your meta data or if you have not already defined ‘title’ in Posts table. You may find complete list of attributes here, feel free to add more/less fields as per your needs.
You can find descriptions for all above added fields in the Gem’s documentation or by doing a quick Google search. Be sure to add all the newly added fields in strong parameters (Rails 4 :-))
Add the new added fields to the Post’s form and… Voila! We are done with setting up our Add/Edit/Update. Now comes the main part, showing meta information for each post in views.
For that to happen, let’s first set all the meta tags using meta-tags’ predefined method set_meta_tags
, which would look something like this:
Now we need to show these meta tags in the head section of our page. But the <head>
section of our views renders in application.html.erb. Hmm? How are we going to get this to work? Not to worry ;-)
Go to your application.html.erb, and in the <head>
section add
In the else section, you may write all the default tags, you want to add to other pages.
Now in Views for post , we write content for <head>
as follows:
where display_meta_tags
is meta-tags gem’s method to display meta tags.
Voila! We just implemented our blogging site with dynamic meta-tags loading.