Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: How do I define an association extension in a module that gets included in my AR model?

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?

like image 834
nfm Avatar asked Feb 03 '11 23:02

nfm


1 Answers

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
like image 166
Benjamin Oakes Avatar answered Nov 15 '22 03:11

Benjamin Oakes