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:
[codesyntax lang=”rails”]
gem ‘slugged’, ‘~> 2.0’
[/codesyntax]
Modify our model:
[codesyntax lang=”rails”]
class Product < ActiveRecord::Base .. is_sluggable :title, :slug_column=>:slug, :history => false, :to_param=>false, :editable => false end
[/codesyntax]
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:
[codesyntax lang=”rails”]
row = Product.find_using_slug('apple-juice')
[/codesyntax]
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:
[codesyntax lang=”rails”]
class Product < ActiveRecord::Base
..
is_sluggable :title, :slug_column=>:slug, :history => false, :to_param=>true, :editable => false
end
[/codesyntax]
After this we will have the following URLs:
[codesyntax lang=”rails”]
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”
[/codesyntax]