具有 ActiveRecord 模型的代理对象 - method_missing 有时不起作用
我一直在使用应用程序的模型作为定义行为的其他对象的代理。
class Box < ActiveRecord::Base
belongs_to :box_behavior, :polymorphic => true, :validate => true, :foreign_key => 'box_behavior_id', :dependent => :destroy
[...]
def initialize(opts = {})
super(opts)
self.box_behavior = BoxBehaviorDefault.new if self.box_behavior.blank?
end
private
def method_missing(method, *args, &block)
super
rescue NoMethodError
return self.box_behavior.send(method,*args,&block)
end
end
因此,我在 BoxBehavior 对象上实现了所有方法,当我在 box 实例上调用方法时,它会将调用重定向到关联的 boxbehavior 对象。一切正常,除了当我尝试在我的购买模型上创建一个钩子时,它从其盒子对象中获取总数并保存它:
class Purchase < ActiveRecord::Base
belongs_to :box
before_validation_on_create { |r| r.total = r.box.total }
end
当我尝试保存任何具有关联盒子的购买对象时,我收到此错误:
undefined method `total' for #<ActiveRecord::Associations::BelongsToAssociation:0x7fe944320390>
并且我不知道下一步该做什么...当我直接在盒子类中实现总方法时,它工作正常...我能做些什么来解决这个问题?代理不能正常工作吗?
I've been using a model of my application as a proxy to other objects that define behavior.
class Box < ActiveRecord::Base
belongs_to :box_behavior, :polymorphic => true, :validate => true, :foreign_key => 'box_behavior_id', :dependent => :destroy
[...]
def initialize(opts = {})
super(opts)
self.box_behavior = BoxBehaviorDefault.new if self.box_behavior.blank?
end
private
def method_missing(method, *args, &block)
super
rescue NoMethodError
return self.box_behavior.send(method,*args,&block)
end
end
So I implement all the methods on my BoxBehavior objects, and when I call a method on a box instance then it redirects the call to the associated boxbehavior object. It all works fine except when i tried to create a hook on my purchase model where it gets the total from its box object and saves it:
class Purchase < ActiveRecord::Base
belongs_to :box
before_validation_on_create { |r| r.total = r.box.total }
end
When I try to save any purchase object that has a box associated, I get this error:
undefined method `total' for #<ActiveRecord::Associations::BelongsToAssociation:0x7fe944320390>
And I don't have a clue on what to do next... When I implement the total method directly in the box class then it works fine... what can I do to solve this? Isn't the proxy working properly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我发现 Rails 并不总是使用初始化来创建模型的新实例。所以我使用了 after_initialize 钩子并解决了问题!
I found out that Rails doesn't always use initialize to create a new instance of a model. So i used the hook after_initialize and solved the problem!