Rails:通过belongs_to查询has_one在查询中添加PK空值

时间:2019-06-15 20:48:19

标签: ruby-on-rails rails-activerecord

尝试查询关系时出现错误。这些是我的模型:

class Course < ApplicationRecord
  belongs_to :subject, inverse_of: :courses
  # This is the important relation
  has_one :department, through: :subject
end

class Subject < ApplicationRecord
  belongs_to :department, inverse_of: :subjects
  has_many :courses, dependent: :destroy, inverse_of: :subject
end

class Department < ApplicationRecord
  has_many :subjects, dependent: :destroy
end

问题是,如果我这样做:

> Course.where(department: Department.first)
  Department Load (0.3ms)  SELECT  `departments`.* FROM `departments` ORDER BY `departments`.`id` ASC LIMIT 1
  Course Load (0.7ms)  SELECT `courses`.* FROM `courses` WHERE `courses`.`id` IS NULL
=> []

如您所见,它包含一个WHERE courses.id IS NULL。无论如何,我可以通过以下方式访问此关系:

> Course.joins(:subject).where(subjects: { department: Department.first })
  Department Load (0.4ms)  SELECT  `departments`.* FROM `departments` ORDER BY `departments`.`id` ASC LIMIT 1
  Course Load (0.5ms)  SELECT `courses`.* FROM `courses` INNER JOIN `subjects` ON `subjects`.`id` = `courses`.`subject_id` WHERE `subjects`.`department_id` = 1

作为结果,我得到了许多对象,但是我想知道是否缺少某种东西来使它起作用。

顺便说一句,如果我尝试直接访问该方法,它将正常工作:

> Course.first.department
  Course Load (0.9ms)  SELECT  `courses`.* FROM `courses` ORDER BY `courses`.`id` ASC LIMIT 1
  Department Load (0.6ms)  SELECT  `departments`.* FROM `departments` INNER JOIN `subjects` ON `departments`.`id` = `subjects`.`department_id` WHERE `subjects`.`id` = 1 LIMIT 1
=> #<Department:0x00007fc40dfab5f8
 id: 1,
 name: "Matemática",
 slug: "matematica",
 code: 1,
 created_at: Sat, 15 Jun 2019 20:49:33 UTC +00:00,
 updated_at: Sat, 15 Jun 2019 20:49:33 UTC +00:00>

谢谢!

0 个答案:

没有答案