Search code examples
ruby-on-railsrubyruby-on-rails-3activerecordmixins

Is a valid approach to state Active Record Associations in mixin modules?


I am using Ruby on Rails v3.2.2 and I would like to know if it is a valid approach to state a Active Record Association in a mixin module. Why?

More:

  1. what are advantages and disadvantages of this approach?
  2. is there something to which I should pay attention to?
  3. is there some prescription to make that?

Note: I would like to DRY (Don't Repeat Yourself) my code since statements related to my Active Record Associations are the same for multiple models.


Solution

  • Go ahead and do it! Regarding your questions:

    • Regarding 1: The biggest advantage is that you have a clean code base with no duplicated code; the biggest disadvantage I can think of is that it might not be instantly obvious to someone looking through your code.

    • Regarding 3: You have to define the associations either in the included callback or using the new ActiveSupport::Concern extensions for it.

    Example:

    # using the standard include callback
    module LocationAwareness
    
      def self.included(base)
        base.has_one :location
      end
    end
    

    or

    # using ActiveSupport::Concern
    module LocationAwareness
      extend ActiveSupport::Concern
    
      included do
        base.has_one :location
      end
    end
    

    then you can use it in your models like that:

    class Person < ActiveRecord::Base
      include LocationAwareness
    end
    
    class Gig < ActiveRecord::Base
      include LocationAwareness
    end
    
    #...
    

    This approach of course starts to make even more sense if you have more shared behaviour than "just" the association...