这是我的like.rb模型
class Like < ActiveRecord::Base
attr_accessible :user_id, :post_id
before_save :increment_post_total_likes
before_destroy :decrement_post_total_likes
scope :desc_ordered, :order => "created_at DESC"
belongs_to :post
belongs_to :user
def increment_post_total_likes
p = Post.find(self.post_id)
p.increment!(:total_likes)
p.save
end
def decrement_post_total_likes
p = Post.find(self.post_id)
p.decrement!(:total_likes)
p.save
end
def self.alreadyLiked(post_id, user_id)
where(:user_id => user_id, :post_id => post_id).any?
end
def self.already_liked?(user_id)
exists?(:user_id => user_id)
end
end
问题是,当我喜欢一个帖子时,它会增加帖子 total_likes
列,但也会增加另一个表列,这两个列共享关联的列,例如 post_id
和 user_id
我不明白为什么...
我只想在点赞表上使用 before_save 和 before_destroy
最佳答案
增量!
将 save the record for you 。尝试一下,不要 panic 。
关于mysql - ruby on Rails before_save 增加表的不同列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12249434/