ruby on rails:搜索关联

时间:2016-10-27 17:52:27

标签: ruby-on-rails search associations where

我几乎没有理解问题:

我有ChannelLecturer,其中Channel :has_and_belongs_to_many :lecturers

我希望获得所有频道,其中Lecturer.id是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

这不起作用,我觉得我不理解核心概念,因为我可以做到

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

我错过了什么?

1 个答案:

答案 0 :(得分:3)

您想要加入表格来执行此查询。见the docs

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