FriendlyId Gem Tutorial
Ruby On Rails MVC model allows us to structure our URLs in a very intuitive and friendly way for Google/Bing Search Engines to consume. However, Ruby on Rails out of the box URL mapping with is usually done via routing mapping is not optimized to use titles of your object instances. It relies on system IDs stored in the database.
As a result, several Ruby on Rails gems were developed by the community and we would like to introduce one such gem called FriendlyId. You can find this gem on Git at the following address: https://github.com/norman/friendly_id
In order to set up this gem with your Rails project you need to include reference to it in your Gem file such as
gem "friendly_id", "~> 5.0.1"
Please consult FriendlyId documentation for the latest gem available for use.
Next step is to run
> bundle install
Please note that FriendlyId gem requires you to have field with the name “slug” and datatype string provisioned in the database.
CREATE TABLE products
(
id serial NOT NULL, title character varying NOT NULL, slug character varying, description character varying, meta_title character varying, meta_description character varying, meta_keywords character varying, ) WITH ( OIDS=FALSE );
After you define this table either via SQL or migration files in Ruby
class CreateProducts < ActiveRecord::Migration def change create_table :products do |t| t.string :title, :null => false t.string :slug t.string :description t.string :meta_title t.string :meta_description t.string :meta_keywords end end end
You need to include reference to FriendlyId gem in your model class. In our example, we are adding FriendlyId to our Product class by adding extend FiendlyId and identifying that field we want FriendlyId use as a candidate for URL link leading to an instance of our Product object. FriendlyId provides you with additional mechanism of adding unique url in case there are duplicates in the database. You can see that ther are two entries in the slug_candiates: :title and [:title, :id]. In case when slug with the name you try to create already in the database, FriendlyId will create new slug by using original title and appending unique id for the record.
class Product < ActiveRecord::Base
extend FriendlyId has_many :images has_many :variants friendly_id :title, use: [:slugged, :finders] def slug_candidates [ :title, [:title, :id] ] end end
Finally, you can reference your Product instances via the following Rails link_to helper in order to add FriendlyId path to your application.
<%= link_to variant.product.title, product_path(variant.product) %>