Rails:渴望加载模型三个关联

时间:2015-06-13 04:35:53

标签: ruby-on-rails ruby-on-rails-4 activerecord associations

我想在表格列中显示所有日程表以及相关类,合作伙伴和位置的表格。

# view
<% @schedules.each do |schedule| %>
  <%= schedule.date.strftime("%d %b %Y") %>
  <%= schedule.klass.name %>
  <%= schedule.partner.company %>
  <%= schedule.partner.city.name %>
  <%= schedule.start_time.strftime("%l:%M%P") %> -
  <%= schedule.end_time.strftime("%l:%M%P") %>
<% end %>

# models
Schedule 
  belongs_to :klass
  belongs_to :partner
Klass
  belongs_to :partner
Partner
  belongs_to :city
  has_many   :klasses
  has_many   :schedules
City
  none

# controller Schedules
@schedules = Schedule.includes(:klass, :partner).order(:date, :start_time, :end_time)

不幸的是,当页面加载时,它会多次运行city个查询。

SELECT "schedules".* FROM "schedules"  ORDER BY "schedules"."date" ASC, "schedules"."start_time" ASC, "schedules"."end_time" ASC
SELECT "klasses".* FROM "klasses" WHERE "klasses"."id" IN (6, 1, 7, 9, 10, 3)
SELECT "partners".* FROM "partners" WHERE "partners"."id" IN (3, 4, 2)
SELECT "cities".* FROM "cities" WHERE "cities"."id" = $1 LIMIT 1  [["id", 23]]
SELECT "cities".* FROM "cities" WHERE "cities"."id" = $1 LIMIT 1  [["id", 24]]

我试过了:

Schedule.includes(:klass, :partner).includes(:city)

但它给了我这个错误:

Association named 'city' was not found on Schedule; perhaps you misspelled it?

我已阅读有关活动记录查询的Rails指南,但我不知道如何改进查询。任何帮助赞赏。感谢。

2 个答案:

答案 0 :(得分:0)

Schedule 
  belongs_to :klass
  belongs_to :partner
Klass
  has_many   :schedules
  has_many :partners, through: :schedules
Partner
  belongs_to :city
  has_many   :schedules
  has_many   :klasses, through: :schedules

City
  has_many :partners

查询应为

@schedules = Schedule.includes(:partner => :city).order(:date, :start_time, :end_time).select('partners.*, cities.name')

答案 1 :(得分:0)

知道了:

@schedules = Schedule.includes(:klass, partner: :city).order(:date, :start_time, :end_time)

结果:

SELECT "schedules".* FROM "schedules"  ORDER BY "schedules"."date" ASC, "schedules"."start_time" ASC, "schedules"."end_time" ASC
SELECT "klasses".* FROM "klasses" WHERE "klasses"."id" IN (6, 1, 7, 9, 10, 3)
SELECT "partners".* FROM "partners" WHERE "partners"."id" IN (3, 4, 2)
SELECT "cities".* FROM "cities" WHERE "cities"."id" IN (23, 24)