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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With