rails scope通过has_many关联

时间:2014-06-05 20:41:58

标签: ruby-on-rails-4 scope associations has-many

我有两个模特用于表演和表演(在戏剧或喜剧节目中表演)。它们在模型中如下关联:

class Show < ActiveRecord::Base
  has_many :performances, :dependent => :destroy
  accepts_nested_attributes_for :performances
end

class Performance < ActiveRecord::Base
  belongs_to :show
end

在Performance模型中有一个名为start_time的日期时间。

如何在模型中定义范围,该范围返回至少具有以下性能的所有节目:start_time是将来的?

另外,如何定义一个范围,该范围返回所有不具有以下性能的节目:start_time是将来的?

1 个答案:

答案 0 :(得分:7)

class Show < ActiveRecord::Base
   has_many :performances, :dependent => :destroy
   accepts_nested_attributes_for :performances

   scope :shows_with_pending_performance, includes(:performances).where("performances.start_time >= ? ", Date.today)
end

class Performance < ActiveRecord::Base
   belongs_to :show
end