【发布时间】:2015-08-06 16:20:13
【问题描述】:
我目前正在开发一个网站,家长可以在该网站上为他们的孩子预订课程。在父母的仪表板中,我想显示一个日程表,在每一行中都会有与日程相关联的孩子的名字。不幸的是,我在父母的仪表板中按日期排序时间表时遇到问题。
# 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 模型中有一个默认范围,它按日期、开始时间和结束时间排序。
# Schedule model
default_scope { order(:date, :start_time, :end_time) }
此范围适用于其他表,但不适用于此查询:
# controller
@reservations = current_user.reservations.includes(:child, schedule: [:partner, :klass, :city])
它只是拒绝在浏览器中按日期和时间排序:
日志显示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
但是我会遇到问题,因为每个课程表只能显示一个孩子的名字,因为课程表可以有很多孩子与之关联。
帮助?
【问题讨论】:
-
生成的 SQL 显示它确实按计划排序
-
对我来说不是很清楚到底发生了什么;您希望按日程安排预订吗?
-
@Pavan 它似乎使用 Reservation 的数据库 id 进行订购。
-
我的意思是
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 -
好吧,您没有做任何影响预订订购的事情;时间表将在内预订。
标签: ruby-on-rails ruby-on-rails-4