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

标签 mysql ruby-on-rails associations sql-update

这是我的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/

相关文章:

mysql - 如何创建一个 capistrano 任务来下载最新的 database_backup.tgz 并在本地导入?

ruby-on-rails - 我在 rails generate devise :install 之前运行了 rails generate devise MODEL

javascript - "item_translation is not associated to item!" Sequelize 错误

ruby-on-rails - ActiveRecord:如何克隆嵌套关联?

ruby-on-rails - 设计没有 session cookie 的 token_authenticable

MySQL 不更新 information_schema,除非我手动运行 ANALYZE TABLE `myTable`

mysql - 删除两列都不存在的记录

php - 存储在mysql中编码的信息

ruby-on-rails - Form_For New 相关模型

mysql - 带有 JOINS 的多个表