我不确定这是因为我使用的是 Rails 4,但我很困惑。
I have the following models set:
class Post < ActiveRecord::Base
has_many :stars, :as => :starable, :dependent => :destroy
belongs_to :user
end
class Star < ActiveRecord::Base
before_create :add_to_total_stars
belongs_to :starable, :polymorphic => true
protected
def add_to_total_stars
if [Post].include?(starable.class)
self.starable.update_column(:total_stars, starable.total_stars + self.number)
end
end
end
class User < ActiveRecord::Base
has_many :posts, dependent: :destroy
has_many :votes, dependent: :destroy
end
所以我在 Rails 控制台中创建了一个星号和一个帖子:
star = post.stars.build number: 2
post = Post.create title: "test", content: "test", user_id: 1
然后使用以下内容修改中的average_stars
列post
:
star.starable.update(:average_stars, 4)
到目前为止一切正常:
star.starable
=> #<Post id: 9, title: "test", content: "test", created_at: "2013-07-25 16:05:52", updated_at: "2013-07-25 16:05:52", user_id: 1, average_stars: 4, total_stars: 0.0>
但后来我想检查一下post
,我看到了这个:
post
=> #<Post id: 9, title: "test", content: "test", created_at: "2013-07-25 16:05:52", updated_at: "2013-07-25 16:05:52", user_id: 1, average_stars: 0, total_stars: 0.0>
average_stars
根本没有更新。
为什么 update_column 更新了 star.starable 而不是帖子?