Custom slugs in Rails using gem Slugged

There are several gems to have slug in a model in Rails application: friendly_id, slugged and some others.

Friendly_id seems to be very powerful. FriendlyId is an add-on to Ruby’s Active Record that allows you to replace ids in your URLs with strings

Slugged is much simpler, but enough to solve common problems while dealing with slugs.

This post shows how to have a column to store slug.

 

Requirements:

– for our model (Product) we want to have column named ‘slug’ to have a slug version of column ‘title’

– slug must be updated every time title is changed

 

Solution

First we add column ‘slug’ to our table ‘products’.

Add gem to Gemfile:

gem 'slugged', '~> 2.0'

Modify our model:

class Product < ActiveRecord::Base
 
..
 
    is_sluggable :title, :slug_column=>:slug, :history => false, :to_param=>false, :editable => false
 
end

 

That’s it!

In this example, we do not track the history of changes of slug.

Every time you change a product’s title it will update its slug.

 

Find by slug

To find product by slug:

row = Product.find_using_slug('apple-juice')

It will find the product with title ‘Apple juice’.

 

Friendly URLs

To have better URLs like ‘/product/apple-juice’¬† instead of ‘/products/5’ we use option¬†:to_param=>true in our model:

class Product < ActiveRecord::Base
..
  is_sluggable :title, :slug_column=>:slug, :history => false, :to_param=>true, :editable => false
end

After this we will have the following URLs:

row = Product.find_using_slug('apple-juice')
    url_edit = edit_product_path(row)  # "/products/apple-juice/edit"
    url_show = product_path(row)       # "/products/apple-juice"