模型范围奇怪的结果

时间:2015-06-04 11:00:12

标签: ruby ruby-on-rails-4

我的模型上有以下范围。

class ProgrammeInstance  < ActiveRecord::Base
  # more code

  scope :published, -> { where(published: true) }
  scope :order_by_start_date, -> { order(:start_date) }
  scope :future_with_offset, -> { where("start_date >= ?", Date.today - 7.days) }
  scope :upcoming_with_offset, -> { future_with_offset.published.order_by_start_date }

  # more code
end

我使用范围来查询从rails返回的列表

programme_instances.upcoming_with_offset

返回空结果集。但是,如果我使用范围的内容而不是范围本身进行调用,那么

programme_instances.future_with_offset.published.order_by_start_date

我收到了结果。

必须有一些我不了解范围的东西。任何人都可以解释原因吗?

感谢。

1 个答案:

答案 0 :(得分:0)

class ProgrammeInstance  < ActiveRecord::Base
  scope :future_with_offset, -> { where(condition) }
  scope :published, -> { where(published: true) }
  scope :order_by_start_date, order('start_date')
end

您可以在控制器中将其称为

ProgrammeInstance.future_with_offset.published.order_by_start_date