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:
- what are advantages and disadvantages of this approach?
- is there something to which I should pay attention to?
- 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.
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
includedcallback or using the newActiveSupport::Concernextensions for it.Example:
or
then you can use it in your models like that:
This approach of course starts to make even more sense if you have more shared behaviour than “just” the association…