简体   繁体   中英

activerecord query for an array of arrays

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?

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 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM