使用“has_many"扩展插件中的模型使用模块 [英] Extend model in plugin with "has_many" using a module
问题描述
我在包含一些模型的引擎样式插件中有一些代码.在我的应用程序中,我想扩展这些模型之一.通过在初始化程序中包含一个模块,我设法将实例和类方法添加到相关模型中.
I have a some code in an engine style plugin which includes some models. In my app I want to extend one of these models. I have managed to add both instance and class methods to the model in question by including a module from within an initializer.
但是我似乎无法添加关联、回调等.我收到找不到方法"错误.
However I cannot seem to add associations, callbacks etc. I get a 'method not found' error.
/libs/qwerty/core.rb
/libs/qwerty/core.rb
module Qwerty
module Core
module Extensions
module User
# Instance Methods Go Here
# Class Methods
module ClassMethods
has_many :hits, :uniq => true # no method found
before_validation_on_create :generate_code # no method found
def something # works!
"something"
end
end
def self.included(base)
base.extend(ClassMethods)
end
end
end
end
end
/initializers/qwerty.rb
/initializers/qwerty.rb
require 'qwerty/core/user'
User.send :include, Qwerty::Core::Extensions::User
推荐答案
我认为这应该可行
module Qwerty
module Core
module Extensions
module User
# Instance Methods Go Here
# Class Methods
module ClassMethods
def relate
has_many :hits, :uniq => true # no method found
before_validation_on_create :generate_code # no method found
end
def something # works!
"something"
end
end
def self.included(base)
base.extend(ClassMethods).relate
end
end
end
end
end
旧代码错误导致在模块加载时调用验证和关联,并且该模块对ActiveRecord一无所知.这是 Ruby 的一个通用方面,加载时直接调用类或模块主体内的代码.你不想那样.要解决这个问题,您可以使用上述解决方案.
The old code is wrong cause the validation and the association are called upon module loading, and this module knows nothing about ActiveRecord. That's a general aspect of Ruby, code inside class or module bodies is called directly when loaded. You don't want that. To get around that you can use the above solution.
这篇关于使用“has_many"扩展插件中的模型使用模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!