Rails 3 STI模型中的意外回调行为

时间:2013-03-31 17:24:46

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

无法弄清楚为什么会发生这种情况:

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有一个'type'attr)。组和用户都可以有很多条。

以下按预期工作(some_method不会被调用):

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

以下调用some_method:

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

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

3 个答案:

答案 0 :(得分:0)

Group.create.belongings << Bar.new永远不会将Bar保存到数据库中。因此永远不会调用after_save。第二个示例使用保存到数据库的update_attributes。这就是它触发after_save的原因。

答案 1 :(得分:0)

这是STI和多态的混合。您的Foo模型应具有belongsable_type和belongsable_id属性。

我不能完全击落它,但改变你的比较应该有效:

belongable_type == "User"

答案 2 :(得分:0)

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

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