Adding Open Graph Meta To Your Rails App

If you're looking for a way to add the necessary Open Graph meta data to your Rails app, here's a quick example and tutorial to help you. 

Why is it important? Well one, if you plan on posting links to your content on a Facebook page, the only way Facebook gets things such as your description, title, and featured image would be through the Open Graph meta data.

So let's start. This example is shown as if you had a blog or page with articles. In the case of Railscoder.com, I use post(s) as my model/controller but call them articles.

I started by creating a partial called _og_meta.html.erb inside my partials folder. Then placed the partial in my application layout between the head tags.

<%= render partial: "partials/og_meta" %>

You would need to adjust the path based on the name of the folder you keep your partial in.

Then inside the _og_meta.html.erb file, I have the following meta attributes:

<meta property="og:url" content="<%= request.url %>" />
<meta property="og:type" content="<%= yield :og_type %>" />
<meta property="og:title" content="<%= yield :og_title %>" />
<meta property="og:description" content="<%= yield :og_description %>" />
<meta property="og:image" content="<%= yield :og_image %>" />

As you can see with the URL property, I am simply using the request.url command. But with the others, I am setting them dynamically based on the article or page that is being requested.

So now on the Post/Article Show page, add these to top of the page:

<% content_for :og_type, "article" %>
<% content_for :og_title, @post.title %>
<% content_for :og_description, truncate(strip_tags(@post.content.body.to_s), length: 250) %>
<% content_for :og_image, polymorphic_url(@post.featured_image) %>

Remember, you don't need to populate data for the URL since that is using the global variable for request.url.

But the other attributes are calling for data yield from your various pages. For type, I have simply used "article." But for the other attributes, I am using dynamic data from the selected post. After you have added the necessary content_for tags, your site should be running with accurate Open Graph meta data and will display the correct images, titles, and descriptions when shared on Facebook.

0 Comments


Please log in to leave a reply.