Skip to content

Instantly share code, notes, and snippets.

@pietromoro
Last active May 10, 2023 10:05
Show Gist options
  • Select an option

  • Save pietromoro/6cfbd500b8cec4b79e1383f6ebccba32 to your computer and use it in GitHub Desktop.

Select an option

Save pietromoro/6cfbd500b8cec4b79e1383f6ebccba32 to your computer and use it in GitHub Desktop.
Sluggable rails concern: use slugs instead of ids in the url!
module Sluggable
extend ActiveSupport::Concern
cattr_reader :slugging
included do
before_save :generate_slug
def self.sluggable
all.extending(Sluggable::Finder)
end
def self.slugging attribute
@@slugging = attribute.to_sym
end
end
def to_param?
return nil unless persisted?
slug
end
module Finder
def find(*args)
id = args.first
return super if args.count != 1
resource = resource_by_slug(id)
resource ||= super
raise ActiveRecord::RecordNotFound unless resource
resource
end
private
def resource_by_slug(id)
find_by(slug: id)
end
end
private
def generate_slug
return unless send("#{slugging}_changed?".to_sym)
self.slug = send(slugging).parameterize
end
end
@pietromoro
Copy link
Author

Hey! yes, you are right, I came across the same problem long time ago and always forgot to fix it in this gist. Did it now! Thanks for the heads up!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment