Rorshark
Rorshark

Reputation: 87

How do I optimize this chain of associations?

I have an Event model with a many-to-many association with a Service model

A user can create an event and choose what services are tagged to that event.

A user can subscribe to a service, and when an event gets created the user should be notified if the user has subscribed to a service that was tagged in that event.

In addition, the User model has a has_many association to an Email model.

I'd like to be able to get an array of all the email addresses so I can send a notification to the subscribers.

Here's what I have:

class Event < ActiveRecord::Base

  has_many :event_services, :dependent => :destroy
  has_many :services, :through => :event_services

  def recipients
    recipients = services.each_with_object(arr = []) do |service|
      service.users.each do |user|
        user.emails.each do |email|
          arr << email.address
        end
      end
    end
  end
  recipients.uniq
end

This works, but its super ugly and not very efficient. How would I go about optimizing this?

Here's my Email model:

class Email < ActiveRecord::Base
  attr_accessible :address, :user_id  
  belongs_to :user
end

Upvotes: 1

Views: 702

Answers (1)

Baldrick
Baldrick

Reputation: 24340

It would be more efficient with a single SQL request The following request, using multiple joins, should work:

def recipients
  Email.joins(:user => {:services => :event_services}).where(:event_services => {:event_id => self.id}).pluck(:address).uniq
end

Upvotes: 3

Related Questions