rails scope through has_many association
Asked Answered
W

1

7

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?

Why answered 5/6, 2014 at 20:41 Comment(3)
what's your question?Sardinia
I thought it was clear. I'll rephrase it as questions. There are two.Why
ok...@KevinM if my suggestion was right, please confirm it as solutionSardinia
S
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
Sardinia answered 6/6, 2014 at 13:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.