I have a Blockable
module that contains associations and methods to be included in a few other ActiveRecord
classes.
Relevant code:
module Blockable
def self.included(base)
base.has_many :blocks
end
end
I want to add an association extension. The usual syntax (ie when I'm not defining the association in a module) is like this:
# definition in Model < ActiveRecord::Base
has_many :blocks do
def method_name
... code ...
end
end
# usage
Model.first.blocks.method_name
This syntax doesn't work when used in the module which is included in the AR model. I get an undefined method 'method_name' for #<ActiveRecord::Relation:0xa16b714>
.
Any idea how I should go about defining an association extension in a module for inclusion in other AR classes?
Rails 3 has some helper methods for this. This example is from The Rails 3 Way, 2nd Edition:
module Commentable
extend ActiveSupport::Concern
included do
has_many :comments, :as => :commentable
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With