【发布时间】:2014-11-11 21:19:05
【问题描述】:
我的应用有两个模型,ClassSection 和 ClassDate(这些模型中的课程是指学校的课程)。
以下是模型:
class ClassSection < ActiveRecord::Base
default_scope { order('code ASC') }
scope :published, -> { order('code ASC').order('id ASC').where(published: true) }
has_many :class_dates, dependent: :destroy
def begins
if self.class_dates.count > 0
self.class_dates.order('start_time ASC').first.start_time
else
nil
end
end
def ends
if self.class_dates.count > 0
self.class_dates.order('start_time ASC').last.start_time
else
nil
end
end
def date_range
if self.begins != nil && self.ends != nil
"#{self.begins.to_formatted_s(:class_date)} to #{self.ends.to_formatted_s(:class_date)}"
else
"No dates"
end
end
end
class ClassDate < ActiveRecord::Base
scope :upcoming, -> { where("start_time >= ? ", Time.now.to_date).order('start_time ASC').limit(10) }
default_scope { order('start_time ASC' ) }
belongs_to :class_section
end
在 :published ClassSections 的范围内请注意,我首先根据类的代码(如 ENG 101)进行排序,然后按 id 进行排序。我宁愿根据它的 start_time(这是 ClassDate 的日期时间属性)对第一个 ClassDate 进行排序。如何编写按最早 start_time 排序的范围?
如需解答,请查看Sorting a hash using a method from the corresponding model
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-4 scope has-many