bdx
bdx

Reputation: 3516

Making this ActiveRecord lookups more efficient

I want to get an array of all email addresses for users of certain service types.

Using a string of ActiveRecord has_many relations, I can get these like this:

affected_services = Service.where(service_type: 'black')
affected_accounts = affected_services.map {|s| s.account}
affected_emails = affected_accounts.map {|a| a.contact.email}

I know it would be a fairly simple SQL query, but I'd prefer to see if ActiveRecord can do it to keep database abstraction.

Is there a good ActiveRecord way to retrieve those results?

Upvotes: 0

Views: 34

Answers (1)

Rob Falken
Rob Falken

Reputation: 2297

You could use :include to include children in the query.

Account.find(:all, :include => :contact, :conditions => {:service_id => Service.where(:service_type => 'black').map{|account| account.contact.email } })

Upvotes: 0

Related Questions