How to add a Ruby on Rails association from inside a module/mixin

Sometimes you have several models that don’t just similar functionality but similarly named associations, and it’d be good practice to define those associations in a mixin. Doing so however is a bit of a black art. I found out how to do this from www.teachmetocode.com (and the code below includes the hint from Stefan Kanev’s comment).

Solution

Write a module similar to the following, the include it from your models in order to gain access to the association.

module AssociationModule
  def self.included(base)
    base.has_many :things, :class_name => "#{base.name}Thing"
  end
end
Advertisements

About this entry