Reputation: 2464
I have the following models:
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
I want to grab all the notifications where the sent_email is false for all users who set their alert frequency to 1, and I want the return result to be something like this:
[
{user object => [<all of the notifications for user 1>]},
{user object => [<all of the notifications for user 2>]}
]
I want it to be 1 or 2 queries at most.
What would the activerecord query look like?
Upvotes: 0
Views: 465
Reputation: 118299
You can use includes
.
u = User.includes(:received_notifications, :alert)
.where("alerts.frequency_discussion_alerts = ? AND notifications.sent_email = ?", 1, false)
.references(:notifications,:alerts)
Now in batch, you can fetch users and do your job.
u.find_each { |u| u.received_notifications }
Upvotes: 2