Rails:如何在包含在我的AR模型中的模块中定义关联扩展?

nfm*_*nfm 5 activerecord ruby-on-rails associations ruby-on-rails-3

我有一个Blockable模块,其中包含要包含在其他几个ActiveRecord类中的关联和方法.

相关代码:

module Blockable
  def self.included(base)
    base.has_many :blocks
  end
end
Run Code Online (Sandbox Code Playgroud)

我想添加一个关联扩展名.通常的语法(即当我没有在模块中定义关联时)是这样的:

# definition in Model < ActiveRecord::Base
has_many :blocks do
  def method_name
    ... code ...
  end
end

# usage
Model.first.blocks.method_name
Run Code Online (Sandbox Code Playgroud)

在AR模型中包含的模块中使用时,此语法不起作用.我得到了undefined method 'method_name' for #<ActiveRecord::Relation:0xa16b714>.

知道如何在模块中定义关联扩展以包含在其他AR类中吗?

Ben*_*kes 7

Rails 3有一些辅助方法.这个例子来自The Rails 3 Way,2nd Edition:

module Commentable
  extend ActiveSupport::Concern
  included do
    has_many :comments, :as => :commentable
  end
end
Run Code Online (Sandbox Code Playgroud)


nfm*_*nfm 2

唉,我烂透了。

我有一个不相关的错误导致关联扩展中断。

我已经验证我的原始方法和 Xavier Holt 的方法都可以在 Rails 3.0.3 下工作:

self.included(base)
  base.has_many :blocks do 
    def method
      ...
    end
  end
end

# OR

self.included(base)
  base.class_eval do 
    has_many :blocks do
      def method
        ...
      end
    end
  end
end
Run Code Online (Sandbox Code Playgroud)