gpt4 book ai didi

mysql - ruby on Rails before_save 增加表的不同列

转载 作者:行者123 更新时间:2023-11-29 14:18:04 24 4
gpt4 key购买 nike

这是我的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_iduser_id 我不明白为什么...

我只想在点赞表上使用 before_save 和 before_destroy

最佳答案

增量!save the record for you 。尝试一下,不要 panic 。

关于mysql - ruby on Rails before_save 增加表的不同列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12249434/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com