【发布时间】:2014-02-25 15:30:54
【问题描述】:
我有一个模型,我想根据关联模型来确定其范围。这是模型,ClassSection 和 ClassDate。
class ClassSection < ActiveRecord::Base
has_many :class_dates
accepts_nested_attributes_for :class_dates, allow_destroy: true
def begins
self.class_dates.order('start_time ASC').limit(1).first.start_time
end
def ends
self.class_dates.order('end_time DESC').limit(1).first.end_time
end
end
每个 ClassDate 都有两个日期时间值,:start_time 和 :end_time。
class ClassDate < ActiveRecord::Base
belongs_to :class_section
validates :start_time, :presence => true
validates :end_time, :presence => true
validate :end_time_must_be_greater_than_start_time,
:end_time_must_not_be_greater_than_24_hours_after_start_time
def end_time_must_be_greater_than_start_time
if start_time > end_time
errors.add(:end_time, "End time must be after start time.")
end
end
def end_time_must_not_be_greater_than_24_hours_after_start_time
if start_time < end_time - 1.day
errors.add(:end_time, "End time cannot be more than 24 hours after start time.")
end
end
end
我想要一个名为 :in_session 的范围,其中今天的日期介于 class_section.begins 和 class_section.ends 之间。这不起作用:
scope :in_session, where(class_section.begins < Time.now) && where(class_section.ends > Time.now)
是否可以使用我编写的方法或通过与 ClassDate 的关联来确定范围?最有效的方法是什么?
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-4 scope associations has-many