where子句中的范围

时间:2011-12-04 13:58:12

标签: ruby-on-rails

您可以看到这两个模型的最后几行使用相同的代码:

class Position < ActiveRecord::Base
  scope :last_day, 
  where('positions.created_at > ? AND positions.hidden = ?',
  DateTime.now.in_time_zone("Sofia").yesterday.beginning_of_day + 10.hours, false)
end

class Subscriber < ActiveRecord::Base
  scope :notify_today,
  joins(:tags => :positions).
  where('positions.created_at > subscribers.created_at 
  AND positions.created_at > ? AND positions.hidden = ?', 
  DateTime.now.in_time_zone("Sofia").yesterday.beginning_of_day + 10.hours, false)
end

是否可以在第二个模型中以某种方式重复使用'last_day'范围?

1 个答案:

答案 0 :(得分:2)

where()joins()都返回ActiveRecord::Relation个对象,并且它们有一个名为merge()的方法,可以合并其他ActiveRecord::Relation个对象。因此,您可以简单地执行此操作

scope :notify_today, joins(:tags => :positions).merge(Position.last_day)

另外,&merge()的别名,所以你也应该能够这样做

scope :notify_today, joins(:tags => :positions) & Position.last_day