我正在使用redis和Rails为我的webapp创建一个点击计数器。
我在Redis中保存视图,然后每天更新数据库中的值。
要增加视图,我使用此方法:
def self.async_increase_visits
$redis.hkeys('video_visits').each do |id|
self.find(id).increase_visit($redis.hget('video_visits', id))
$redis.hdel('video_visits', id)
end
end
def increase_visit(visits)
self.increment!(:impressions_count, visits.to_i)
end
我注意到生成的查询是:
Loading staging environment (Rails 4.0.0)
2.0.0-p353 :001 > Content.async_increase_visits
Content Load (5.1ms) SELECT "contents".* FROM "contents" WHERE "contents"."id" = $1 ORDER BY published_at DESC LIMIT 1 [["id", "12300"]]
(0.3ms) BEGIN
ContentElement Load (7.8ms) SELECT "content_elements".* FROM "content_elements" WHERE "content_elements"."content_id" = $1 ORDER BY "content_elements".position ASC [["content_id", 12300]]
SQL (15.7ms) UPDATE "contents" SET "impressions_count" = $1, "updated_at" = $2 WHERE "contents"."type" IN ('News') AND "contents"."id" = 12300 [["impressions_count", 3], ["updated_at", Fri, 02 May 2014 18:58:30 CEST +02:00]]
SQL (15.5ms) UPDATE "comments" SET "commentable_state" = 'published', "commentable_url" = '#' WHERE "comments"."id" IN (SELECT "comments"."id" FROM "comments" WHERE "comments"."commentable_id" = $1 AND "comments"."commentable_type" = $2 ORDER BY comments.created_at asc) [["commentable_id", 12300], ["commentable_type", "Content"]]
(1.7ms) COMMIT
=> ["12300"]
2.0.0-p353 :002 > Content.async_increase_visits
Content Load (1.1ms) SELECT "contents".* FROM "contents" WHERE "contents"."id" = $1 ORDER BY published_at DESC LIMIT 1 [["id", "12448"]]
(0.2ms) BEGIN
ContentElement Load (0.8ms) SELECT "content_elements".* FROM "content_elements" WHERE "content_elements"."content_id" = $1 ORDER BY "content_elements".position ASC [["content_id", 12448]]
SQL (2.9ms) UPDATE "contents" SET "impressions_count" = $1, "updated_at" = $2 WHERE "contents"."type" IN ('News') AND "contents"."id" = 12448 [["impressions_count", 2], ["updated_at", Fri, 02 May 2014 18:59:10 CEST +02:00]]
SQL (4.7ms) UPDATE "comments" SET "commentable_state" = 'published', "commentable_url" = '#' WHERE "comments"."id" IN (SELECT "comments"."id" FROM "comments" WHERE "comments"."commentable_id" = $1 AND "comments"."commentable_type" = $2 ORDER BY comments.created_at asc) [["commentable_id", 12448], ["commentable_type", "Content"]]
(1.2ms) COMMIT
=> ["12448"]
我的内容有很多评论(多元关联),但我不明白为什么要简单的"增量"我也在协会中更新了一些价值。
如何仅更新impressions_count
值?
答案 0 :(得分:1)
increment!
方法调用回调。如果您只需更新此列以跳过回调和验证,则可以使用update_counters
方法。
def increase_visit(visits)
Content.update_counters(self.id, impressions_count: visits.to_i)
end