查找对象时,如何按表中的字段对其获取的子对象进行排序

问题描述 投票:0回答:1

假设有一个预订系统可以预订特定活动的时间段。

我有一个事件模型和一个time_slot模型。每个事件都有man time_slots,每个槽都属于一个事件

class Event < ActiveRecord::Base
  has_many :time_slot
end

class TimeSlot < ActiveRecord::Base
  belongs_to :event
end

当我做Event.find(some_id)时,如何根据模型上的字段订购返回的时隙,例如'slot_time'

ruby-on-rails ruby ruby-on-rails-5 rails-activerecord
1个回答
3
投票

像这样:

Event.find(some_id).time_slot.order(:slot_time)

time_slot实际上并没有返回所有相关的时隙,它返回一个ActiveRecord :: Relation,就像TimeSlot.where(booked: true)那样。因此,您可以将更多查询方法链接到此关系。

© www.soinside.com 2019 - 2024. All rights reserved.