Skip to content

Instantly share code, notes, and snippets.

@onesup
Created November 19, 2016 16:48
Show Gist options
  • Save onesup/3f5758d848e02b445e4dd30ceff70611 to your computer and use it in GitHub Desktop.
Save onesup/3f5758d848e02b445e4dd30ceff70611 to your computer and use it in GitHub Desktop.
의도: 새로운 QueryLog 가 생성되면, 같은 keyword 를 가지고 있는 오늘 생성된 모든 QueryLog 를 카운팅해서 Keyword 객체의 daily_query_logs 에 업데이트 해준다.
삽질: update_daily_query_logs_count 함수 안에서 QueryLog 를 조회하면,
새로 생성되는 해당 객체가 가지고 있는 attribute 를 사용해서 조회를 한다.
설명이 좀 어려운데, 그냥 단순하게 QueryLog.all.to_sql 로 조회를 해도
SELECT `query_logs`.* FROM `query_logs`
WHERE `query_logs`.`user_id` = 5 AND `query_logs`.`keyword_id` = 2
AND (`query_logs`.`created_at` BETWEEN '2016-11-19 15:00:00' AND '2016-11-19 16:40:12')
라는 sql 문이 출력된다.
class QueryLog < ApplicationRecord
belongs_to :keyword, counter_cache: true
belongs_to :user
after_create :update_daily_query_logs_count
protected
def update_daily_query_logs_count
today_count = QueryLog.where(keyword: keyword, created_at: Time.now.beginning_of_day..Time.now).count
binding.pry
keyword.update(daily_query_logs_count: today_count + 1)
end
end
From: /Users/onesup/projects/today-novel/app/models/query_log.rb @ line 10 QueryLog#update_daily_query_logs_count:
8: def update_daily_query_logs_count
9: today_count = QueryLog.where(keyword: keyword, created_at: Time.now.beginning_of_day..Time.now).count
=> 10: binding.pry
11: keyword.update(daily_query_logs_count: today_count + 1)
12: end
[1] pry(#<QueryLog>)> QueryLog.all
QueryLog Load (0.4ms) SELECT `query_logs`.* FROM `query_logs` WHERE `query_logs`.`user_id` = 5 AND `query_logs`.`keyword_id` = 2 AND (`query_logs`.`created_at` BETWEEN '2016-11-19 15:00:00' AND '2016-11-19 16:40:12')
=> [#<QueryLog:0x007f8b90668960
id: 27,
keyword_id: 2,
user_id: 5,
created_at: Sun, 20 Nov 2016 01:40:12 KST +09:00,
updated_at: Sun, 20 Nov 2016 01:40:12 KST +09:00>]
[2] pry(#<QueryLog>)>
@onesup
Copy link
Author

onesup commented Nov 19, 2016

결론: unscoped 를 사용하면 된다. QueryLog.unscopes.where ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment