假设我有三个模型:组织、技能和评估。
评估能否通过不同的关系属于两个不同的组织?
例如,评估可能发生在组织 A,但基于属于组织 B 的技能。
以下是我的模型和关联:
class Organization < ActiveRecord::Base
has_many :checklists
has_many :levels, :through => :checklists
has_many :sections, :through => :levels
has_many :skills, :through => :sections
has_many :assessments_using_own_checklists, :through => :skills, :source => :assessments
end
class Skill < ActiveRecord::Base
belongs_to :section
has_one :level, through: :section
has_one :checklist, through: :level
has_one :organization, through: :checklist
has_many :assessments
end
class Assessment < ActiveRecord::Base
belongs_to :skill
has_one :section, through: :skill
has_one :level, through: :section
has_one :checklist, through: :level
has_one :checklist_owner, through: :checklist, source: :organization
belongs_to :organization
end
使用上述方法,我可以获得评估的组织:
Assessment.last.organization # yields organization 1
我还可以获得评估checklist_owner:
Assessment.last.checklist_owner # yields organization 2
但是当我尝试在where
中使用checklist_owner
时,协会似乎忘记了使用:through
。例如,如果我运行:
Assessment.where(organization: Organization.find(2), checklist_owner: Organization.find(1))
。这转换为 SQL:
SELECT "assessments".* FROM "assessments" WHERE "assessments"."organization_id" = 2 AND "assessments"."organization_id" = 1
看看 SQL 如何有两个"assessments"."organization_id" =
语句?它为什么要这样做?
你试过用joins
吗?
像这样:
Assessment.joins(skill: { section: { level: :checklist } }).where(organization: Organization.find(2), checklists: { organization_id: Organization.find(1) })
我知道它看起来很糟糕,但似乎你从评估到清单的关系非常复杂。这将处理任何奇怪的关系。