Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails scope through has_many association

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?

like image 936
Kevin K Avatar asked Jun 05 '14 20:06

Kevin K


1 Answers

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
like image 169
enrique-carbonell Avatar answered Oct 06 '22 13:10

enrique-carbonell