How To Create Search Friendly Urls in Rails

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
app/models/post.rb
extend FriendlyId
friendly_id :slug_candidates, use: [:slugged, :finders, :history]

 def slug_candidates 
	[ :title,
	 [:title, :id]
	 ] 
end
Add slug attribute to the Post model
rails g AddSlugToPosts slug:string
add_column :posts, :slug, :string
add_index :posts, :slug, unique: true
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.
Related Posts

Leave a Comment

Your email address will not be published. Required fields are marked *

en_USEnglish