简体   繁体   中英

Chain scopes between models in Rails

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?

If you are adding conditions on associations, you also need to join them , not only merge or include them, ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM