【问题标题】:Rails - incrementing integers from db with concurrencyRails - 从数据库中并发递增整数
【发布时间】:2014-06-06 16:25:22
【问题描述】:

在我们的数据库中,我们有一个commentsblogs 的表。

有一个字段 comments.comment_blog_index 会随着博客中的每条评论而递增。

...所以如果我们有 3 个特定博客的 cmets,则每个评论的 comment_blog_index 的值是:123(分别)

设置comment_blog_index 的代码如下所示:

@comment = Comment.new
@comment.comment_blog_index = @blog.comments.count + 1

当两个用户同时触发此代码时会出现问题。它将为两个用户计算相同的值,并且 comment_blog_index 是重复的。

我已经看到Item.increment_counter( :total_bids, item.id ) 的代码,但这要求您已经在数据库中的一个表中存储了一个记录,该表存储了一个总和。在我们的例子中,记录是在 `commments` 表中创建的。

我们如何防止这种情况发生?

【问题讨论】:

    标签: ruby-on-rails concurrency


    【解决方案1】:

    正如您已经看到的那样,您当前的方法并不安全。您可以添加验证和回调以及各种方式来尝试使其安全,但我建议这种工作应该在数据库级别进行。

    implement a propert auto-incrementing fieldoffload that work to a gem

    【讨论】:

      【解决方案2】:

      这会有所帮助 Generate an auto increment field in rails 它展示了如何在 rails 中实现自动增量

      【讨论】:

      • 代码示例总是受欢迎的,比只是一个链接更好;)
      • 感谢您的建议,先生。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-04
      • 1970-01-01
      • 2016-10-23
      • 1970-01-01
      • 2014-08-06
      相关资源
      最近更新 更多