ruby-on-rails - 使用事件记录回调来更新模型属性

标签 ruby-on-rails ruby-on-rails-3 activerecord

假设我有一个处理帖子评论的Rails应用程序。一篇文章有​​有很多条评论,每条评论都属于一篇文章。

每个评论都有一个word_count 属性。 Post 对象有一个 average_comment_word_count 属性,它是每个评论的 word_count 的平均值。

当我针对特定评论发送 DELETE 请求时,应用应重新计算 average_comment_word_count 参数。我认为它的工作方式是这样的:

class Comment < ActiveRecord::Base

belongs_to :user
belongs_to :post
after_destroy :update_post_average_word_count

def update_post_average_word_count
  post_average_word_count = 0
  post.comments.each do |comment|
     post_average_word_count = post_average_word_count + comment.word_count
  end

  post_average_word_count / post.comments.count
  post.update_attributes average_word_count: post_average_word_count
end

但是,我收到数据库错误,因为应用程序找不到相关帖子的引用(因为评论已消失,请在此处提示 Homer Simpson)

是否有其他方法可以实现此目的?

最佳答案

使用before_destroy并在计算post_average_word_count时考虑到这一点:

post.update_attributesaverage_word_count:(post_average_word_count - self.word_count)

关于ruby-on-rails - 使用事件记录回调来更新模型属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10217228/

相关文章:

ruby-on-rails - 如何在 Rails 6 中使用 Webpacker 跨多个客户端 JavaScript 文件共享变量和函数?

mysql - 从redis切换到Mysql。好主意?

ruby-on-rails - Rails 搜索插件和解决方案

ruby-on-rails-3 - Rails 3 : datetime_select with am/pm options

ruby-on-rails - Rails 中特定于模型的 SQL 日志记录

ruby-on-rails - Rails 中的无表模型

javascript - Rails - 具有不显眼的 javascript Jquery UI 进度条的 Ajax

ruby-on-rails - 如何正确地遍历参数

ruby-on-rails - Rails 窗体 : How to add field beside checkboxes on Many-to-Many Relationship

php - Yii2 效率——外键还是匿名函数?