Search code examples
ruby-on-railssearchassociationswhere-clause

ruby on rails: search through associations


I have little understanding problem:

I have Channel and Lecturer, where a Channel :has_and_belongs_to_many :lecturers.

I want to get all Channels where Lecturer.id is lect.id.

2.3.0 :235 >   Channel.where(:lecturers => { :id => 2 })
  Channel Load (0.1ms)  SELECT "channels".* FROM "channels"  WHERE "lecturers"."id" = 2
SQLite3::SQLException: no such column: lecturers.id: SELECT "channels".* FROM "channels"  WHERE "lecturers"."id" = 2
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: lecturers.id: SELECT "channels".* FROM "channels"  WHERE "lecturers"."id" = 2

This does not work and I feel like I don't understand the core concept, since I can do

2.3.0 :231 > Channel.first.lecturer  
=> #<Lecturer id: 2, name: "Albert Einstein">

What am I missing?


Solution

  • You'll want to join the tables to do this query. See the docs

    Channel.joins(:lecturer).where(lecturers: {id: lect.id})