rails scope through has_many association

Kevin K picture Kevin K · Jun 5, 2014 · Viewed 8.3k times · Source

I have two models for Show and Performance (show as in a play or comedy show). They are associated like this in the models:

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

class Performance < ActiveRecord::Base
  belongs_to :show
end

In the Performance model there is a datetime called :start_time.

How do I define a scope in the model which returns all Shows with at least one performance whose :start_time is in the future?

Also, how do I define a scope that returns all Shows that do not have any performances in whose :start_time is in the future?

Answer

enrique-carbonell picture enrique-carbonell · Jun 6, 2014
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