繁体   English   中英

在rails中确定has_many关系

[英]Scoping through a has_many relationship in rails

我有一个模型,我想根据相关的模型来确定范围。 以下是模型,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的关联来确定范围? 最有效的方法是什么?

是的,这是可能的。 但是,在Rails 4中,您需要使用lambda范围,而不是像您一样急切地加载条件。

尝试:

scope :in_session, -> { joins(:class_section).where('? between class_sections.begins and class_sections.ends', Time.now) }

你的表名class_section是单数的,因为你已经显示了你的范围,它应该是复数class_sections除非你明确指定它是单数。 我在上面的范围中使用了多个class_sections ,如果你的表名是单数,则将它更新为单数class_section

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM