簡體   English   中英

如何在 Rails 中的 has_many::through 關聯上設置 foreign_keys?

[英]How do I set foreign_keys on a has_many: :through association in Rails?

我有 2 個表, ItemItemBelonging 我正在嘗試在items之間創建樹關系。 對於item的每個后代,我創建一個item_belonging來連接該item和后代item

Item {
  id:,
  ...
}

ItemBelonging {
  id:,
  item_id:,
  descendant_id:,
  ...
}

我能夠成功調用item.descendants來接收一個項目的所有后代。 我已經建立了這樣的關系:

class ItemBelonging < ApplicationRecord
  belongs_to :descendant, :class_name => 'Item'
  ...
end

class Item < ApplicationRecord
  has_many :descendants, :through => :item_belongings, :source => :descendant
  ...
end

問題是我希望能夠調用item.ancestors以使用相同的ItemBelonging關系獲取項目的所有祖先。 我可以這樣做:

  def ancestors
    Item.joins(:item_belongings).where("item_belongings.descendant_id = ?", id)
  end

但是如何使用 has_many/belongs_to 創建這種關系呢? 這不起作用:

class ItemBelonging < ApplicationRecord
  belongs_to :descendant, :class_name => 'Item'
  belongs_to :ancestor, :class_name => 'Item', :foreign_key => :item_id
  ...
end

class Item < ApplicationRecord
  has_many :descendants, :through => :item_belongings, :source => :descendant
  has_many :ancestors, :through => :item_belongings, :source => :ancestor, :foreign_key => :descendant_id
  ...
end

我的最終目標是能夠調用Item.includes(:descendants)Item.includes(:ancestors) 我如何讓ancestors關系發揮作用?

使用祖先寶石,您可以輕松使用此類 DSL

class Item < ApplicationRecord
  has_ancestry
end

然后創建一些記錄

parent = Item.create
first_child = Item.create(parent: parent)
second_child = Item.create(parent: parent)
first_child_child = Item.create(parent: first_child)

並開箱即用地使用這些方法

parent.children # => [first_child, second_child]
parent.descendants # => [first_child, second_child, first_child_child]
first_child.siblings # => [first_child, second_child]
first_child.subtree # => [first_child, first_child_child]
first_child_child.parent # => first_child
first_child_child.root # => parent
first_child_child.ancestors # => [parent, first_child]
first_child_child.path # => [parent, first_child, first_child_child]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM