初始化混合到模型中的模块
我有这个:
class Bullet < ActiveRecord::Base
include StagedVersionMethods
...
end
当
module StagedVersionMethods
def initialize
puts self.bullet_id
end
end
我创建 Bullet 实例时,模块初始化方法会触发,但我收到 ActiveRecord 错误: ...activerecord-2.2.2/lib/active_record/attribute_methods.rb:268:in `read_attribute'
我的目的是初始化一个实例变量,我需要为其混合记录的主键值。 然后模块中的其他方法将使用该实例变量。
moduleinclude() 回调也不适合该任务,因为在该上下文中,self 是模块而不是 AR 记录。
应该如何处理这个问题?
谢谢
I have this:
class Bullet < ActiveRecord::Base
include StagedVersionMethods
...
end
And this
module StagedVersionMethods
def initialize
puts self.bullet_id
end
end
When I create an instance of Bullet, the modules initialize method fires, but I get an ActiveRecord error:
...activerecord-2.2.2/lib/active_record/attribute_methods.rb:268:in `read_attribute'
My intent is to initialize an instance variable for which I need the primary key value of the record I'm mixing into. Other methods in the module will then work with this instance variable.
The module included() callback does not fit the task either, because self, in that context, is the Module not the AR record.
How should this be approached?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
覆盖 ActiveRecord 上的初始化程序可能会产生奇怪的副作用,并且难以调试,因此不建议这样做。 推荐的方法是使用 ActiveRecord 提供的 :after_initialize 回调。 您仍然可以通过模块混合这种行为......
Overiding the initializer on ActiveRecord can have strange side effects that prove difficult to debug, so it's not recommended. The recommended approach would be to use the :after_initialize callback that ActiveRecord provides instead. You can still mix this behaviour in via a module...
如果您像这样定义初始化:
那么我认为它将执行您想要的操作,因为它将首先使用 ActiveRecord 初始化为您正确设置对象。 但是,我不确定这种方法对于您想要实现的目标有多稳健。 在访问实例变量时而不是在初始化对象时创建该实例变量可能更合适。
如果不知道你想要实例变量做什么,就很难说。
If you define initialize like:
then I think it will do what you want as it will set up the object correctly for you using the ActiveRecord initialization first. However, I'm not sure how robust that approach is for what you're trying to achieve. It might be more appropriate to create this instance variable when it is accessed rather than when the object is initialized.
It's kind of hard to say without knowing what you want the instance variable to do though.