2016-03-19 7 views
0

Railsでモデル間のクエリに問題があります。私はクラスMessageそのbelongs_to: bookingがあります。私の目標は、Bookingスコープに依存するMessageactiveスコープを追加することです。Railsでのモデル間のチェーンスコープ

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 

は、私は、関連するBookingactiveある特定のPersonに向けMessageのを見つけたいです。したがって、Message.activeを作成する際にBooking.activeを使用したいと考えています。上記の実装でMessage.active(1)を呼び出す

次のエラーが返されます。

Association named 'event' was not found on Message; perhaps you misspelled it?

は、私がMessage.activeの実装でBooking.activeを使用してMessage sが返さ得ることができる方法はありますか?

答えて

1

あなたが組合に条件を追加する場合は、あなたもする必要が彼らにそれらをmergeincludeないだけに参加するには、次の動作するはずすなわち:

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 

この上の多くのドキュメントはありません、見詳細はthisをご覧ください。

関連する問題