[英]Best way to find Users with certain associations
Lets say I have a User
model and each user has an association called user_logins
which is created every time they login, storing information about their login. 假设我有一个
User
模型,每个用户都有一个名为user_logins
的关联,该关联在每次登录时都会创建,并存储有关其登录的信息。
What I need to do is find all users that have 5 user_login records, where the fifth record was created today. 我需要做的是找到所有具有5条user_login记录的用户,今天已在其中创建了第五条记录。
Something like this: 像这样:
users = User.all.where(user_logins_count == 5, user_login.last.created_at == today)
user_logins_count
is a counter cache I have set up. user_logins_count
是我设置的计数器缓存。
Of course that code is brutal, but hopefully it'll elaborate on what I'm trying to achieve. 该代码当然是残酷的,但希望它能详细说明我要实现的目标。
PG ERROR PG错误
rake aborted!
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: missing FROM-clause entry for table "last
"
LINE 1: ...n_logins_count" = 5 GROUP BY humans.id HAVING MAX(human_logi...
^
New code: 新代码:
humans = user.humans.joins(:human_logins).where(human_logins_count: 5)
.group('humans.id')
.having('MAX(human_logins.created_at) >= ?', Date.today)
You can define this as a scope inside the User
class: 您可以在
User
类中将其定义为作用域:
class User
scope :logged_in_a_lot_today, -> do
joins(:user_logins).where(user_logins_count: 5)
.group('users.id')
.having('MAX(user_logins.created_at) >= ?', Date.today)
end
end
Now you can simply get these users with: 现在,您只需使用以下方法即可获得这些用户:
User.logged_in_a_lot_today
Since it's defined as a scope, you can also add more conditions if you'd like to: 由于它被定义为作用域,因此您还可以添加更多条件:
User.logged_in_a_lot_today.where(name: 'John Doe')
Note that it would probably be a good idea to set up a partial index (if your database supports it) on users who have a user_logins_count
of 5. 请注意,为
user_logins_count
为5的用户设置部分索引(如果数据库支持)可能是一个好主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.