【问题标题】:How to specify primary key in a through association如何在直通关联中指定主键
【发布时间】:2016-11-01 21:28:15
【问题描述】:

我有一个图节点类的实现,我希望它具有有向无环图的功能。

联想大致如下

class Node
  has_many :edges

  has_many :parents,
           :foreign_key => 'parent_id',
           :through => :edge

  has_many :parent_edges,
           :foreign_key => 'child_id',
           :class_name => 'Edge',
           :dependent => :destroy

  # similar for children
end

class Edge
  belongs_to :parent,
             :class_name => 'Node'

  # similar for child

  has_many :edge_properties
end

当我尝试获取父节点的关系时,生成的查询仍然使用 node_id 作为主键。

SELECT `nodes`.* 
FROM   `nodes` 
       INNER JOIN `edges` 
               ON `nodes`.`id` = 
                  `edges`.`parent_id` 
WHERE  `edges`.`node_id` = 16             # where clause uses node_id, should be child_id
ORDER  BY `nodes`.`name` ASC 

我该怎么做才能将该查询更改为在 where 子句中使用 child_id

【问题讨论】:

  • 您是否尝试将 :foreign_key => :child_id 放在 Edge belongs_to :parent 行中?另外:你能告诉我们生成那个 SQL 的 Rails 代码吗?

标签: ruby-on-rails activerecord arel directed-acyclic-graphs


【解决方案1】:

正确的解决方案(TIL :through 选项也可以指定另一个关联)

 has_many :parent_edges,
          :foreign_key => 'child_id',
          :class_name => 'Edge',
          :dependent => :destroy

 has_many :parents,
          :source => 'parent',
          :through => :parent_edges  # using another association

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-18
    • 1970-01-01
    相关资源
    最近更新 更多