查找对象时,如何按 table 中的字段对其获取的子对象进行排序
When finding an object, how to order its fetched children objects by fields in their table
假设有一个预订系统可以为某个活动预订时间段。
我有一个事件模型和一个 time_slot 模型。每个事件有mantime_slots,每个slot属于一个事件
class Event < ActiveRecord::Base
has_many :time_slot
end
class TimeSlot < ActiveRecord::Base
belongs_to :event
end
当我做 Event.find(some_id)
如何根据模型上的字段对返回的时隙进行排序,例如 'slot_time'
就像这样:
Event.find(some_id).time_slot.order(:slot_time)
time_slot
实际上并不是 return 所有关联的时隙,它 return 是一个 ActiveRecord::Relation,就像 TimeSlot.where(booked: true)
一样。因此,您可以将更多查询方法链接到此关系。
假设有一个预订系统可以为某个活动预订时间段。
我有一个事件模型和一个 time_slot 模型。每个事件有mantime_slots,每个slot属于一个事件
class Event < ActiveRecord::Base
has_many :time_slot
end
class TimeSlot < ActiveRecord::Base
belongs_to :event
end
当我做 Event.find(some_id)
如何根据模型上的字段对返回的时隙进行排序,例如 'slot_time'
就像这样:
Event.find(some_id).time_slot.order(:slot_time)
time_slot
实际上并不是 return 所有关联的时隙,它 return 是一个 ActiveRecord::Relation,就像 TimeSlot.where(booked: true)
一样。因此,您可以将更多查询方法链接到此关系。