【问题标题】:Scoping through a has_many relationship in rails通过 rails 中的 has_many 关系确定范围
【发布时间】: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


    【解决方案1】:

    是的,这是可能的。然而,在 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-06
      • 2014-07-05
      • 2017-11-11
      • 1970-01-01
      • 2021-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多