我有一个Tracker::Db::Service
具有以下关联的类:
has_many :source_links, class_name: :Link, foreign_key: :source_key, conditions: [ 'state_id = 1 AND source_object_id = 3' ]
has_many :target_links, class_name: :Link, foreign_key: :target_key, conditions: [ 'state_id = 1 AND target_object_id = 3' ]
has_many :work_order_targets, through: :source_links, source: :work_order_as_target, class_name: :WorkOrder
has_many :work_order_sources, through: :target_links, source: :work_order_as_source, class_name: :WorkOrder
然后Tracker::Db::Link
有这些关联:
belongs_to :work_order_as_target, class_name: :WorkOrder, foreign_key: :target_key, conditions: [ 'target_object_id = 11' ]
belongs_to :work_order_as_source, class_name: :WorkOrder, foreign_key: :source_key, conditions: [ 'source_object_id = 11' ]
当我尝试从一个实例中遍历这些关联时,例如:service.work_order_targets
,它工作得很好。
但是,如果我尝试在查询中包含/加入这些,我会遇到问题
Tracker::Db::Service.includes(:work_order_targets).limit(10)
Mysql2::Error: Unknown column 'target_object_id' in 'where clause': SELECT `change_workorder`.* FROM `change_workorder` WHERE `change_workorder`.`id` IN (4262, 4239, 4058, 4062, 4258, 4242, 4240, 4256, 4241, 4253) AND (( target_object_id = 11))
它正在错误地构建查询。我尝试使用哈希语法来指定条件,但这也不起作用,它只是变成了 change_workorder.target_object_id。它在两种关系上都这样做work_order_targets, work_order_sources
Tracker::Db::Service
有id, name
Tracker::Db::Link
有source_object_id, source_key, target_object_id, target_key
Tracker::Db::WorkOrder
_id, name
不幸的是,这是一个第 3 方应用程序数据库(开源项目,OTRS + ITSM 模块),所以我无法真正控制结构,我只是将我们的 Rails 应用程序连接到其中。