Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does slug used for in Rails?

I am reading Hours source code, and there is a class called slug

https://github.com/DefactoSoftware/Hours/blob/development/app/models/concerns/sluggable.rb

And I see every model has an attribute called slug with a string type?

What does slug used for in this case?

Code below is one of the slug used inside the tag model,

class Tag < ActiveRecord::Base
  attr_reader :total_hours
  include Sluggable

  validates :name, presence: true,
                   uniqueness: { case_sensitive: false }

  has_many :taggings
  has_many :hours, through: :taggings
  has_many :projects, -> { uniq }, through: :hours
  has_many :users, -> { uniq }, through: :hours
  belongs_to :project

  def self.list
    Tag.order(:name).pluck(:name)
  end

  private

  def slug_source
    name
  end
end
like image 592
X.Creates Avatar asked Dec 19 '22 09:12

X.Creates


2 Answers

In general, I use it to generate a friendly url. If you prefer, it's human-readable ID that you can use in URL. I think it's SEO friendly as well. You can use like that :

mysite.com/products/xbox360-fifa-15

instead of

mysite.com/products/123456

In your link, if the slug already exists, the method will generate :

mysite.com/products/xbox360-fifa-15-1

Performance : Don't forget to create an index on every slug column you use.

like image 168
devoh Avatar answered Dec 29 '22 09:12

devoh


See the to_param there? https://github.com/DefactoSoftware/Hours/blob/development/app/models/concerns/sluggable.rb#L9-L11

It's for prettier urls. A string will be used instead of integer ids. Say

/tags/ruby-on-rails

instead of

/tags/123412341234
like image 44
Sergio Tulentsev Avatar answered Dec 29 '22 08:12

Sergio Tulentsev