Search code examples
ruby-on-railsmodelsmixins

Mixin to define model associations in Rails 3.1


I have a range of different models which each share a polymorphic association with a Properties model. I'm trying to write a mixin to DRY the code up a bit, but they're not working, please can you offer some debugging help. My mixin looks like this...

module ModelWithProperties
    def self.included?(base)
        base.class_eval do
            has_many :properties, :as=>:parent
        end
    end

    def examplesharedfunction
        /// stuff here
    end
end

And then my models look like this...

class Myobjects < ActiveRecord::Base
    include ModelWithProperties
end

When I run all this, though, the association does seem to have taken ('undefined method 'properies' for #can access the examplesharedfunction.

Any clues/tips?


Solution

  • The hook that gets called when a module is included is self.included not self.included?

    You could also use ActiveSupport::Concern

    module M
      extend ActiveSupport::Concern
    
      included do
        has_many :properties, :as=>:parent
      end
    end