使用update_counters

时间:2016-12-15 19:24:47

标签: ruby-on-rails ruby-on-rails-4 activerecord postgresql-9.1

是否可以使用 update_counters 链接 find_or_create_by

我试图增加" points" 的当前值,并且仅针对特定记录(如果它们尚不存在则需要创建)。因此,如果记录存在,那将只有1个数据库命中。

这样的事情:

Point.where(user_id:4).find_or_create_by(topic_id:107).update_counters(points: 5)

CONTEXT : 用户获得积分取决于他们确实贡献的主题(这可能很多,所以我试图将2个查询减少到1)。 Point属于User和Topic,因此如果用户尚未对某个主题做出贡献,则需要创建一个新的Point记录来存储这些点(user_id,topic_id,points);否则现有记录的点数就会增加。我使用increment!(:points,5)但它击中了数据库两次(选择+更新)。 update_counters 仅使用1个更新查询,但在这种情况下似乎并非如此,因为它的语法不允许我包含我需要的条件。

这样可行,但它会在数据库中击中两次:

Point.where(user_id:4).find_or_create_by(topic_id:107).increment!(:points,5)

0 个答案:

没有答案