我有一个 Blockable
包含关联和方法的模块,这些关联和方法将包含在其他一些 ActiveRecord
中类。
相关代码:
module Blockable
def self.included(base)
base.has_many :blocks
end
end
我想添加一个关联扩展。通常的语法(即当我没有在模块中定义关联时)是这样的:
# definition in Model < ActiveRecord::Base
has_many :blocks do
def method_name
... code ...
end
end
# usage
Model.first.blocks.method_name
在 AR 模型中包含的模块中使用时,此语法不起作用。我得到一个
undefined method 'method_name' for #<ActiveRecord::Relation:0xa16b714>
.知道我应该如何在模块中定义关联扩展以包含在其他 AR 类中吗?
最佳答案
Rails 3 为此提供了一些辅助方法。这个例子来自 The Rails 3 Way, 2nd Edition :
module Commentable
extend ActiveSupport::Concern
included do
has_many :comments, :as => :commentable
end
end
关于ruby-on-rails - rails : How do I define an association extension in a module that gets included in my AR model?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4892847/