3

Quite new to Rails and have run into an issue I just can't seem to figure out.

I have 2 models, User & Post. Users will have a "name" attribute, Posts will have a "title" attribute.

In both cases, I would like to also maintain a slug that will, on before_save, convert the appropriate column to a "sluggified" version and store that as the slug. I've already got the logic I want in place and have had this working, however, I'd like to abstract the behavior into a Concern.

I cannot seem to figure out a way to set this up - mostly because of the dynamic nature of the source field. I'd like to be able to do something like the following:

class User < ActiveRecord::Base
  include Sluggable

  act_as_slug :name
end

class Post < ActiveRecord::Base
  include Sluggable

  act_as_slug :title
end

Unfortunately, no matter what I've tried on the implementation of the concern, I've run into walls.

While I'd like to know what type of implementation is possible either way, I'd also be interested in hearing if this is a good use case for concerns or not?

1 Answer 1

4

This seems to work, in the event anyone else is looking for an answer (definitely open to better suggestions from those with more experience). The models look as suggested in the original post.

module Sluggable
  extend ActiveSupport::Concern

  included do
    before_save :generate_slug
    class_attribute :sluggable_attribute

    def generate_slug
      self.sluggify(self.class.sluggable_attribute)
    end

    def sluggify(attribute)
      # Sluggify logic goes here
    end
  end

  module ClassMethods
    def acts_as_slug(value)
      self.sluggable_attribute = value
    end
  end
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.