Rails没有按日期排序此查询

时间:2015-08-06 16:20:13

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

我目前正在一个网站上工作,父母可以为他们的孩子保留课程。在父母的仪表板中,我想显示一个时间表表格,并且在每一行中都会有一个与时间表相关联的孩子的名字。不幸的是,我在父母的仪表板中按日期订购时间表存在问题。

# view
<% @reservations.each do |reservation| %>
  <%= reservation.child.first_name %>
  <%= reservation.schedule.date %>
  <%= reservation.schedule.start_time %> - <%= reservation.schedule.end_time %>
  <%= link_to reservation.schedule.klass.name, schedule_path(reservation.schedule) %></td>
  <%= link_to reservation.schedule.partner.company, partner_path(reservation.schedule.partner) %></td>
  <%= reservation.schedule.city.name %></td>
<% end %>

# associations
User
  has_many :children, dependent: :destroy
  has_many :reservations
  has_many :schedules, through: :reservations
Child
  belongs_to :user
  has_many   :reservations, dependent: :destroy
  has_many   :schedules, through: :reservations
Reservation
  belongs_to :child
  belongs_to :schedule
  belongs_to :user
Schedule
  belongs_to :city
  belongs_to :partner
  belongs_to :activity
  belongs_to :klass
  has_many   :reservations
  has_many   :children, through: :reservations

我的Schedule模型中有一个默认范围,按日期,start_time和end_time排序。

# Schedule model
default_scope { order(:date, :start_time, :end_time) }

此范围适用于其他表,但不适用于此查询:

# controller
@reservations = current_user.reservations.includes(:child, schedule: [:partner, :klass, :city])

它只是拒绝按浏览器中的日期和时间排序:

Schedule table in parent's dashboard

日志显示正在调度Schedule的查询:

Reservation Load (0.3ms)  SELECT "reservations".* FROM "reservations" WHERE "reservations"."user_id" = $1  [["user_id", 1]]
Child Load (0.4ms)  SELECT "children".* FROM "children" WHERE "children"."id" IN (1, 2, 3)
Schedule Load (0.4ms)  SELECT "schedules".* FROM "schedules" WHERE "schedules"."id" IN (24, 12)  ORDER BY "schedules"."date" ASC, "schedules"."start_time" ASC, "schedules"."end_time" ASC
Partner Load (0.3ms)  SELECT "partners".* FROM "partners" WHERE "partners"."id" IN (2)
Klass Load (0.3ms)  SELECT "klasses".* FROM "klasses" WHERE "klasses"."id" IN (9, 17)
City Load (0.4ms)  SELECT "cities".* FROM "cities" WHERE "cities"."id" IN (28)

我可以在控制器中执行此查询:

@schedules = current_user.schedules

但是我遇到的问题是每个日程表只显示一个孩子的名字,因为课程表可以有很多孩子与之相关联。

帮助?

1 个答案:

答案 0 :(得分:1)

您已在Schedule的默认范围内定义了排序,但您从Reservation提取关系。因此,按照指定的顺序查询计划,但由于您可能正在循环浏览视图中的@reservations,因此您会看到他们的订单,而不是他们的schedules订单。您可以按@reservations表格中的字段订购schedules,如下所示:

@reservations = @reservations.order("schedules.date ASC, schedules.start_time ASC, schedules.end_time ASC")

另请注意,通常不鼓励在模型中定义default_scopeon SOelsewhere),因为它难以管理并且可能导致意外和非直观的影响,尤其是在路上。