具有 ActiveRecord 模型的代理对象 - method_missing 有时不起作用

发布于 2024-09-27 12:59:35 字数 1061 浏览 5 评论 0原文

我一直在使用应用程序的模型作为定义行为的其他对象的代理。

  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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

紫瑟鸿黎 2024-10-04 12:59:35

我发现 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!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文