Display IDs in your URLs can be terrible and wasteful for SEO. In this blog entry, I will demonstrate to you how you can utilize slugs to make your URLs more relevant to the page content. In the first place, we will utilize an implicit arrangement (superseding the to_param strategy) to change the URLs and a while later, we will utilize a gem called friendly_id to produce slugs and keep up a past filled with these slugs. So that search engines index your web pages.
For example: http://www.exaple.com/blogs/1 to http://www.exaple.com/blogs/blog-name
Here, I am creating one sample Rails5 app with post model to illustrate how exactly it’s going to work with the pretty URLs.
rails g scaffold post title:string published:boolean
run rails db:migrate
and create some sample posts(http://localhost:3000/posts/new)
app/models/post.rb
def to_param
title.parameterize
end
All the links will be changed to pretty URLs once you add the above method to your model. Please check on index page where it lists all the posts. However, when you click on that it will show you error page.
Post.find method cannot find the record with id which we are passing in URL. We need to create slugs for the above posts in our db for that model.
Let’s add migration file for the slug
rails g migration AddSlugToPosts slug:string
Open the above mentioned migration file and add uniq index to that sulg. Slug needs to be uniq.
class AddSlugToPosts < ActiveRecord::Migration[5.0]
def change
add_column :posts, :slug, :string
add_index :posts, :slug, unique: true
end
end
run db:migrate
Now, we have to change our show action db query to find_by instead of find method. Because we need to fetch the results based on slug.
Change our set_post method to
def set_post
Post.find_by_slug(params[:id])
end
Now, it’s working as expected with the pretty URLs. What if two records have the same URL since both of those records have the same name. Because .find_by always fetches the first record. To resolve this, before saving slug we can combine record id to the slug the way it is mentioned below:
def add_slug
“#{id}-#{title.parameterize}”
end
So, it will generate like “1-blog-name”. We have a gem called friendly_gem to simply take care of all the above-mentioned scenarios.
Feel free to remove the above mentione code from the sample app because everything is managed by the gem.
Friendly_id gem(Rails 5)
Add the latest gem from rubygem web to the gemfile and run bundle
gem 'friendly_id', '~> 5.1'
rails generate friendly_id
The above command generates an initializer file and a migration file.
run db:migrate
Create some records and change our set_post method to the way it is mentioned below. All the old records have to be regenerated, in case you have any.
def set_post
Post.friendly.find("Joe Schmoe".parameterize)
end
Updating post title
Slug will update automatically when you update the title attribute. But it’s not a good practice to update the slugs too frequently. Application may throw errors while clicking on any of the bookmarked URLs because anyone might have old bookmarks. We need to prevent this by adding history symbol to the use option in your Post model.
def slug_candidates
[
:title,
[:title, :id]
]
end
slug_candidates feature was added in friendlyId 5. It allows us to tell the friendly id gem, what needs to be done in case of duplicate slugs.
The code mentioned above advises FriendlyId that it needs to utilize the slug_candidates technique to make the slug uniq. It will attempt the rundown right from the beginning to the end, so in the case above, it will attempt to produce the slug first utilizing the title, and afterwards, if a post by that title already exists, it will attempt to fix the ID again.
Slugs are the primary things read by search engines. That ought to, as of now, give you an idea on how essential they are. To utilize a slug, first add the slug alternative to the friendly_id assistant in the Post Model.
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “ACCEPT ALL”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent.
This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
Cookie
Duration
Description
cookielawinfo-checkbox-analytics
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional
11 months
The cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy
11 months
The cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.