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:
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.
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...