ActiveRecord发update请求的原子操作

676 查看

用ActiveRecord修改一条数据库记录通常都会发出这种SQL:

UPDATE 'posts' SET 'posts_count' = 1 WHERE 'id' = 38

如果要发出这种:

UPDATE 'posts' SET 'posts_count' = 'posts_count' + 1 WHERE 'id' = 38

就需要使用increment_counter/decrement_counter方法:(注意,这俩都是类方法,使用时要传入对象ID)

Post.increment_counter :posts_count , 38

生成的SQL如下:

UPDATE 'posts' SET 'posts_count' = COALESCE('posts_count', 0) + 1 WHERE ('id'= 38)

这样就是安全的原子增量操作了。COALESCE()函数是用来防止字段为NULL引起错误的。如果需要对一条记录同时操作多个字段,则需要使用update_counters方法:(也是类方法,ID作为第一个参数传入)

Post.update_counters 38 , :posts_count => 2 , :update_calls_count => 1

生成的SQL如下:

UPDATE 'posts' SET 'posts_count' = COALESCE('posts_count', 0) + 2, 'update_calls_count' = COALESCE('update_calls_count', 0) + 1 WHERE ('id' = 38)