我有一个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类中吗?
答案 0 :(得分:7)
Rails 3有一些辅助方法。此示例来自The Rails 3 Way, 2nd Edition:
module Commentable
extend ActiveSupport::Concern
included do
has_many :comments, :as => :commentable
end
end
答案 1 :(得分:4)
我目前在Rails代码(2.3.8)中有类似的功能。我使用了base.class_eval
而不是base.has_many
:
module Blockable
self.included(base)
base.class_eval do
has_many :blocks do
def method_name
# ...stuff...
end
end
end
end
end
哇 - 那是很多空格键......
无论如何,这对我有用 - 希望它也适合你!
答案 2 :(得分: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