【问题标题】:When finding an object, how to order its fetched children objects by fields in their table查找对象时,如何按表中的字段对其获取的子对象进行排序
【发布时间】:2019-02-15 15:30:12
【问题描述】:

假设有一个预订系统来预订某个活动的时间段。

我有一个事件模型和一个 time_slot 模型。每个事件都有man time_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”

【问题讨论】:

  • 善待你的程序员,使用正确的复数has_many :time_slots

标签: ruby-on-rails ruby ruby-on-rails-5 rails-activerecord


【解决方案1】:

就像这样:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-30
    • 2011-05-16
    • 1970-01-01
    • 2017-05-01
    相关资源
    最近更新 更多