Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Using different model fields in ActiveRecord Concern

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?

like image 470
cochranjd Avatar asked Nov 29 '25 20:11

cochranjd


1 Answers

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
like image 169
cochranjd Avatar answered Dec 02 '25 10:12

cochranjd