Last active
December 23, 2015 02:39
-
-
Save davidcelis/6568183 to your computer and use it in GitHub Desktop.
an concern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Sluggable | |
extend ActiveSupport::Concern | |
included do | |
before_create :set_slug | |
validates :slug, uniqueness: { case_sensitive: false } | |
scope :from_param, -> param { find_by(slug: param) } | |
end | |
def to_param() slug end | |
private | |
def set_slug | |
number = 1 | |
begin | |
slug = name.parameterize | |
slug << "-#{number}" if number > 1 | |
number += 1 | |
end while self.class.where(slug: slug).exists? | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment