0

In our database, we have a table for comments and blogs.

There's a field comments.comment_blog_index that increments for each comment in the blog.

...so if we have 3 comments for a particular blog, the value for comment_blog_index for each comment is: 1, 2, 3 (respectively)

The code that sets comment_blog_index looks like this:

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

The problem happens when two users trigger this code simultaneously. It will calculate the same value for both users, and the comment_blog_index is duplicated.

I've seen code for Item.increment_counter( :total_bids, item.id ), but that requires you to already have a record in the database in a table that stores a summation. In our case, the record is being created inside the `commments`` table.

How do we prevent this?

Glenn
  • 59
  • 6

2 Answers2

1

As you've already seen your current method is not safe. You could add validations and callbacks and all manner of things to try and make it safe but I would suggest that kind of work should happen at the database level.

Either implement a propert auto-incrementing field or offload that work to a gem.

Community
  • 1
  • 1
Matt
  • 13,948
  • 6
  • 44
  • 68
-1

It will help Generate an auto increment field in rails It shows how auto increment can be implemented in rails

Community
  • 1
  • 1