我的帖子模型与投票模型具有多态关联:
post.rb:
class Post < ActiveRecord::Base
attr_accessible :title, :content, :total_votes
belongs_to :user
has_many :votes, :as => :votable, :dependent => :destroy
end
vote.rb
class Vote < ActiveRecord::Base
belongs_to :votable, :polymorphic => true
belongs_to :user
before_create :update_total
protected
def update_total
self.votable.total_votes ||= 0
self.votable.total_votes += self.polarity
end
end
正如您在 vote.rb 中所见,我想完成以下任务:
每次创建投票的实例时,我都想更新total_votes
模型实例的votable
列(在这种情况下是帖子的实例) )。
但是没有任何反应,当我为post.votes.create(:polarity => 1)
的帖子创建投票时,该帖子的total_votes
列仍为nil
。
有任何解决此问题的建议吗?
修改
这也不起作用:
class Vote < ActiveRecord::Base
belongs_to :votable, :polymorphic => true
belongs_to :user
before_create :update_total
protected
def update_total
self.votable.total_votes ||= 0
self.votable.total_votes += self.polarity
self.votable.save!
end
end
schema.rb:
create_table "posts", :force => true do |t|
t.string "content"
t.integer "user_id"
t.datetime "created_at"
t.datetime "updated_at"
t.string "title"
t.integer "comments_count", :default => 0, :null => false
t.integer "total_votes"
end
答案 0 :(得分:1)
创建Vote
对象时,Post
对象已存在。您更新它,但您不保存它。请尝试使用以下代码:
def update_total
self.votable.total_votes ||= 0
self.votable.total_votes += self.polarity
self.votable.save!
end