ActiveRecord中的多级连接条件

时间:2018-01-28 12:53:12

标签: ruby-on-rails activerecord

我正在努力为我的Rails ActiveRecord查询中的多级联接设置条件:

class CourseSlot < ApplicationRecord
  belongs_to :course
  has_many :user, through: :course
end

class Course < ApplicationRecord
  has_and_belongs_to_many :users
end

class User < ApplicationRecord
  has_and_belongs_to_many :courses
end

HABTM关联存储在CoursesUsers表中:

create_table "courses_users", id: false, force: :cascade do |t|
  t.bigint "user_id", null: false
  t.bigint "course_id", null: false
end

我想查询用户包含当前用户的任何插槽。我试过了:

current = User.find(current_user_id)
CourseSlot
  .joins(course: :users)
  .where(course: {users: current})

但这给了我一个错误:

SELECT  "course_slots".* 
FROM "course_slots" 
INNER JOIN "courses" ON "courses"."id" = "course_slots"."course_id"
INNER JOIN "courses_users" ON 
  "courses_users"."course_id" = "courses"."id" 
INNER JOIN "users" ON "users"."id" = "courses_users"."user_id" 
WHERE "course"."user_id" = 2 
ORDER BY "course_slots"."id" ASC LIMIT $1  [["LIMIT", 1]]
*** ActiveRecord::StatementInvalid Exception: PG::UndefinedTable: 
ERROR:  missing FROM-clause entry for table "course"

我可以看到该查询缺少FROM子句,但我找不到一种方法让ActiveRecord生成正确的查询,这是徒劳的挣扎!

1 个答案:

答案 0 :(得分:1)

尝试以下代码

CourseSlot.joins(course: :users).where(courses: { users: { id: current_user_id } })

在您的查询表中,名称用作“课程”,但我认为它应该是courses

WHERE "course"."user_id" = 2

我希望这能解决你的问题