Frage

I have a model that I'd like to scope based on an associated model. Here are the models, ClassSection and 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

Each ClassDate has two datetime values, :start_time and :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

I want a scope called :in_session where today's date falls in between class_section.begins and class_section.ends. This does not work:

scope :in_session, where(class_section.begins < Time.now) && where(class_section.ends > Time.now)

Is it possible to scope using either the methods I've written or through the association with ClassDate? What would be the most efficient way to do this?

War es hilfreich?

Lösung

Yes it's possible. In Rails 4 however, you need to use lambda scope and not eagerly load the conditions as you've done.

Try:

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

Your table name class_section is singular as you've shown your scope, it should be plural class_sections unless you've explicitly specified it to be singular. I've used plural class_sections in the scope above, update it to singular class_section if your table name is singular.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top