【问题标题】:Rails 3 Unexpected Callback Behavior in STI modelRails 3 STI 模型中的意外回调行为
【发布时间】:2013-03-31 17:24:45
【问题描述】:

不知道为什么会这样:

class Foo < ActiveRecord::Base
  belongs_to :belongable, :polymorphic => true

  def after_save 
    if belongable.kind_of?(User)
      send(:some_method)
    end
  end
end

class Bar < Foo

  def some_method
    #Do something
  end
end

class Group < ActiveRecord::Base
  has_many :belongings, :as => :belongable
end

class User < ActiveRecord::Base
  has_many :belongings, :as => :belongable
end

“Bar”类是从 Foo 继承的 STI 模型(Foo 具有“类型”属性)。组和用户都可以有很多条。

以下按预期工作(some_method 没有被调用):

g = Group.create
g.belongings << Bar.new
g.save

以下调用some_method:

Group.first.belongings.first.update_attributes(:attr => :val)

如何/为什么?!一旦关联已经存在,为什么不评估 'after_save' 回调中的条件?

【问题讨论】:

    标签: ruby-on-rails ruby polymorphism associations sti


    【解决方案1】:

    Group.create.belongings &lt;&lt; Bar.new 从不将 Bar 保存到数据库中。所以after_save 永远不会被调用。第二个示例使用update_attributes,它确实保存到数据库中。这就是它触发after_save的原因。

    【讨论】:

    • 感谢您的回复。但是为什么当父类是组而不是用户时,回调中的条件评估为真,因此调用'some_method'?
    【解决方案2】:

    这是 STI 和多态性的混合体。你的 Foo 模型应该有belongable_type 和belongable_id 属性。

    我无法完全将其击落,但将您的比较更改为此应该可以:

    belongable_type == "User"
    

    【讨论】:

    • 感谢您的回复。试过这个没有用。
    【解决方案3】:

    “some_method”不能称为“更新”... :-/

    AR 对象已经定义了一个名为 update (http://apidock.com/rails/ActiveRecord/Persistence/update) 的方法,并且当您调用“update_attributes”时会调用此方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-17
      相关资源
      最近更新 更多