Category Archives: Ruby On Rails

#RubyOnRails – Friendly_id Gem

Ruby on Rails (or Rails) is a web development framework that gives Rails developers a time-saving method for writing code. Rails are one of many web frameworks in the world of app programming and web development. These frameworks are collections of code libraries that give app and web developers readymade solutions for time-consuming, repetitive tasks—things like building menus, tables, or forms on a website.

Rather than having to write every single line of code in a program from scratch, web developers can refer to a framework and find the code for common functions that they can plug into the websites or web apps they’re building.

Rails render individual records via their id and that is something unfriendly and unmeaningful. Developers may be looking at SEO or even having a simple of accessing a particular record would have to take additional steps to make sure that the URL is taken care of.

Introducing Friendly_id gem, created and maintained by Norman Clarke

 “FriendlyId is the “Swiss Army bulldozer” of slugging and permalink plugins for Active Record. It lets you create pretty URLs and work with human-friendly strings as if they were numeric ids.”

At the time of writing this, the gem is currently at version 5.2.5.

Setup

Add the following line to your Gemfile

Switch to the terminal and run the following

Configuration

We will need to generate a configuration file for Friendly_id

Followed by creating a migration for the model that you are looking to provide a “friendly” id. I will use Book as my model and you should replace it with yours.

Next run the migration script.

Extending the model

There’s a trick here, a lot of folks on Stack Overflow is having issue extending FriendlyId. Make sure you spell it “FriendlyId” instead of “FriendlyID“, note the “D”.

If you are following so far, you have almost reach the end of the setup but if your existing model have some records, we will need to manually create the slug.

Bring up the Rails Console.

Enter the following to have it run a series of update statements.

And we are done.
I strongly recommend that you check out the github repository for other gotcha and as well as stack overflow.

You may need to update all .find() statement to friendly.find() but I will leave that you and I will not cover that.

Friendly_id – https://github.com/norman/friendly_id

Stack Overflow – https://stackoverflow.com/search?q=friendly_id+gem