0

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?

1 Answer 1

2

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 }
Sign up to request clarification or add additional context in comments.

8 Comments

Thanks @R_O_R but it returns all the records in a single array. Is there a way to get all the notifications for each specific reciever_id in its own array inside of an array?
@PavanKatepalli Yes.. call map and build you hash.
@PavanKatepalli what is your db client ? Postgresql?
The issue with .map could be that I have 20,000 notifications to map over. Do you see that being an issue?
@PavanKatepalli try, .select("users.id*, notifications.*").group("users.id") ... map is not a good idea for large data.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.