user1129657
user1129657

Reputation: 17

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?

Upvotes: 0

Views: 521

Answers (1)

Frederick Cheung
Frederick Cheung

Reputation: 84114

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

Upvotes: 4

Related Questions