我有以下型号:
Notification
belongs_to :receiver, class_name: 'User'
# has a sent_email boolean column default set to false
User
has_many :received_notifications, class_name: 'Notification', foreign_key: 'receiver_id', inverse_of: :receiver
has_one :alert
Alert
belongs_to :user
# has a frequency integer column
对于将警报频率设置为1的所有用户,我想抓取sent_email为false的所有通知,并且我希望返回结果如下:
[
{user object => [<all of the notifications for user 1>]},
{user object => [<all of the notifications for user 2>]}
]
我希望它最多是1个或2个查询。
activerecord查询会是什么样的?
答案 0 :(得分:2)
您可以使用includes
。
u = User.includes(:received_notifications, :alert)
.where("alerts.frequency_discussion_alerts = ? AND notifications.sent_email = ?", 1, false)
.references(:notifications,:alerts)
现在批量处理,您可以获取用户并完成工作。
u.find_each { |u| u.received_notifications }