Reputation: 509
I'm having some trouble querying between models in Rails. I have a class Message
that belongs_to: booking
. My goal is to add an active
scope to Message
that depends on a Booking
scope.
class Booking < ActiveRecord::Base
has_one :event
has_many :messages
def self.active
includes(:event).
where('events.endtime >= ? AND status IS NOT ?'
Time.current.beginning_of_week,
statuses['canceled'])
end
end
class Message < ActiveRecord::Base
belongs_to :booking
belongs_to :person
self.active(person_id)
where(person_id: person_id).merge(Booking.active)
end
end
I want to find the Message
s directed to a specific Person
where the associated Booking
is active
. I therefore wish to use the Booking.active
when creating Message.active
.
Calling Message.active(1)
with above implementation returns the following error:
Association named 'event' was not found on Message; perhaps you misspelled it?
Is there any way I can use Booking.active
in the implementation of Message.active
and get Message
s returned?
Upvotes: 0
Views: 302
Reputation: 15944
If you are adding conditions on associations, you also need to join them, not only merge
or include
them, i.e. the following should work:
class Booking < ActiveRecord::Base
# ...
def self.active
joins(:event).
where('events.endtime >= ? AND status IS NOT ?'
Time.current.beginning_of_week,
statuses['canceled'])
end
end
class Message < ActiveRecord::Base
# ...
self.active(person_id)
where(person_id: person_id).joins(:booking).merge(Booking.active)
end
end
There is not much documentation on this, see this for more info.
Upvotes: 1