Adding Structured Data to Rails Applications: Enhancing SEO through Schema Markup
In the realm of Search Engine Optimization (SEO), the adage that content is king cannot be overstated. However, it is essential to note that content is not solely comprised of what users can see or read; metadata plays a crucial role in effectively conveying what the content represents and the entities that are involved.
This article will delve into the process of integrating structured data, commonly known as schema markup, within a Rails application. For those who are unfamiliar with this topic, we will begin with a foundational understanding of structured data.
What is Structured Data?
Structured data, or schema markup, refers to a specific form of metadata that can be embedded into web pages to assist search engines in comprehending the essence of the content. While meta tags in Rails applications serve a similar purpose, structured data categorizes content using a predetermined method involving entities and their properties.
This categorization enables search engines to grasp the context of the content and the relationships between entities. For example, structured data can inform search engines that a specific page pertains to:
- A product: Details such as price, availability, reviews, and discounts can be included.
- A book: Information like ISBN, number of pages, and a brief summary can be provided.
- A recipe: Ingredients, cooking time, and calorie count are all valuable data points.
- A person: Attributes like name, birthdate, email, and phone number can be shared.
Moreover, structured data also represents various entities present on a page, contributing to a comprehensive understanding of the content. Such entities can include:
- Breadcrumbs
- Frequently Asked Questions (FAQs)
- Multimedia elements such as audio, images, or videos
- User-generated content including comments, reviews, and quotes
- Organizational details like logos
By leveraging structured data and its relationships, search engines can achieve a clearer understanding of what our content conveys, as well as the entities represented within it.
The Origins of Schema Markup
Schema markup was developed in 2011 through the collaborative efforts of tech giants Google, Bing, and Yahoo. This initiative aimed to standardize the definition of structured data on the internet, thereby providing semantic meaning and context to entities on web pages using a common language. As of 2024, over 45 million web domains utilize schema markup on their web pages.
Why Should I Add Structured Data to My Application?
There are two primary motivations for incorporating structured data into your website or application:
- Enhancing visibility: By aiding search engines and bots in better understanding the content and the entities it represents, structured data can significantly boost a sites visibility. This, in turn, can improve click-through rates (CTR) on search engine results pages (SERPs), leading to better rankings and increased traffic.
- Expanding query reach: A deeper understanding of the content and its entities may allow search engines to rank the content for queries that it otherwise might not have ranked for.
While structured data offers numerous benefits, it is important to note that it is not classified as a direct ranking factor. Instead, it can indirectly influence better rankings if the resulting improved CTR indicates a positive user experience, signaling to search engines that the content meets users' expectations. As such, you may implement structured data on a webpage without observing immediate improvements in rankings or traffic, but consider it a valuable indirect tool in your SEO arsenal.
What Will We Build?
This article will build upon a fictional book directory application named Buk, which has been previously used to illustrate how to add a sitemap to a Rails app. Our goal is to enrich the information provided to search engines by incorporating structured data into this application.
While structured data could be added directly to the Book or Article models or through partials, we will leverage the schema_dot_org gem. This gem provides invaluable data validation and typing capabilities, which are especially beneficial when managing numerous pages and entities on a website.
Specifically, we will be adding the following entities to the appropriate pages:
- WebSite: Including the SearchAction to facilitate book searches from the homepage.
- Organization
- Breadcrumb
- Book
- Review
If you are curious about the implementation details, you can view the application repository.
Setup
There are various formats available to represent structured data in our Rails application. However, to adhere to search engine recommendations, we will focus on JSON-LD, which stands for JavaScript Object Notation for Linked Data. This format allows us to declare structured data as JSON, which we will then include within the document's <head>
section.
Now, lets explore how to add structured data using both methods: without using a gem and utilizing the schema_dot_org gem.
Adding Structured Data Without a Gem
In Rails, structured data can be added without the assistance of a gem in a couple of ways. The first method involves declaring the data as a hash within a specific model:
class User def to_json_ld { "@context": "https: "@type": "Person", "name": username, "url": "https: } end end
Following the declaration, we can integrate this Person information into another schema type, such as denoting the author of an article, or directly embedding it into the <head>
of a page:
<%= content_for(:head) do %> <script type="application/ld+json"> <%= @user.to_json_ld %> </script> <% end %>
Another approach involves using namespaced Plain Old Ruby Objects (POROs) to represent the desired entities for structured data. Each object would need to be defined within the Schema namespace to avoid conflicts, and it will require an object upon construction, in addition to responding to the to_json_ld
method. The implementation is as follows:
module Schema class ImageObject include Rails.application.routes.url_helpers def initialize(image) @image = image end def to_json_ld { "@context": "https: "@type": "ImageObject", "url": rails_blob_url(@image), "height": @image.metadata[:height], "width": @image.metadata[:width] } end private def default_url_options Rails.application.config.action_mailer.default_url_options || { host: 'localhost:3000' } end end end
Next, a similar class for articles would be defined:
module Schema class Article def initialize(article) @article = article end def to_json_ld { "@context": "https: "@type": "Article", "author": @article.user.to_json_ld, "name": @article.title, "url": "https: "image": Schema::ImageObject.new(@article.cover).to_json_ld, "description": @article.excerpt, "articleBody": @article.content, "publisher": { "@type": "Organization", "name": "AvoHQ", "url": "https: }, "datePublished": @article.published_at, "dateModified": @article.updated_at } end end end
This results in structured data that encapsulates necessary article details and can be rendered appropriately within the application.
Adding Structured Data Using a Gem
To streamline our process, we will utilize the schema_dot_org gem, which offers functionalities for defining and validating structured data to ensure accurate rendering.
To start, we will add and install the gem with the following command:
$ bundle add schema_dot_org && bundle install
As of the time of writing, the gem produces invalid results due to the inclusion of a contextForValidation
attribute in the generated JSON. While there is an open pull request to resolve this issue, we will utilize a fork of the gem:
gem "schema_dot_org", git: "https:This fork not only addresses the context issue but also provides enhancements for defining schemas.
Upon installation, the gem comes equipped with predefined entities located in the lib/schema_dot_org
directory. Among these entities are:
- Person
- Place
- Product
- WebSite
- Organization
- SearchAction
- ItemList
Unlike the previous PORO methodology, the classes within the gem do not require model instances or other Ruby objects; instead, they accept individual attributes such as name or URL.
To define a person, for instance, we would use the following syntax:
person = SchemaDotOrg::Person.new(name: "Exequiel Rozas", url: "https:person.to_json_ld
This produces the output:
<script type= "application/ld+json"> { "@context": "https:</script>
We can include this script directly in the document's <head>
section or utilize the content_for
helper:
<%= content_for(:head) do %> <%= @person %> <% end %>
While the gem offers a limited set of schema types, we can extend its functionality by defining new classes within the SchemaDotOrg
namespace that inherit from SchemaType
.
Conclusion
This article has provided a comprehensive overview of how to integrate structured data into a Rails application through schema markup. By following the guidelines laid out here, developers can significantly enhance their sites visibility on search engines, thereby improving user engagement and overall traffic. Incorporating structured data not only aids in SEO but also creates a more navigable and enriched content experience for users.
As you proceed to implement structured data in your Rails applications, remember to validate your markup using tools like the schema.org validator to ensure compliance and accuracy. With over 800 schema types available, exploring the possibilities for your specific use case can be an exciting next step. Happy coding!