问题
Alright, so we have Accounts which has many Schedules which has many Impressions.
I want to get Accounts.name, all of Accounts.schedules, but only plucking Accounts.schedules.date, Accounts.schedules.summary and also the count of Accounts.schedules.impressions
Here's a visualization of what I want given 1 account (I'll want all accounts)
Account:
.name
Schedules
.date
.summary
count(Schedule.impressions)
And here's what the code would look like with too many queries
Account.find_each do |account|
puts a.name # Account.name
a.schedules.each do |schedule|
puts schedule.date # Account.schedule.date
puts schedule.summary # Account.schedule.summary
puts schedule.impressions.count # Count(Account.schedule.impressions)
I'd like to do this in as few queries as possible, and maybe learn something too! I love efficiency and optimizations.
回答1:
Use a select Query
Account.
joins(schedules: :impressions).
select("accounts.name as account_name,
schedules.date as schedule_date,
schedules.summary as schedule_summary,
count(impressions.id) as schedule_impression_count" ).
group("accounts.name,schedules.date,schedules.summary")
Should do it in a single query then the objects will respond the the column alias' like schedule_date and schedule_impression_count
If you need to use these objects for other data in the same view then Account.eager_load(schedules: :impressions) should also work and will also execute a single query.
来源:https://stackoverflow.com/questions/37081020/activerecord-pluck-specific-columns-and-associations-association-counts