沿着我有一個子組件模型,它可以屬於其他子組件。我的模型是這樣的:在ActiveRecord的關係返回名稱與外鍵ID
class SubComponent < ApplicationRecord
belongs_to :parent, class_name: "SubComponent", foreign_key: "parent_sub_component_id", optional: true
has_many :child_sub_components, class_name: "SubComponent", foreign_key: "parent_sub_component_id"
validates_presence_of :name
end
這種模式是相當簡單的,它有一個name
場和顧名思義是另一個SubComponent
的id
一個parent_sub_component_id
。
我想生成返回所有SubComponents
的(他們id
,name
和parent_sub_component_id
),而且還包括它的實際名稱是parent_sub_component查詢。
這似乎應該是很簡單,但對我的生活我無法弄清楚如何做到這一點。我想要在數據庫中完成這個查詢,而不是在Ruby中做每個循環或類似的事情。
編輯:
我想對於輸出是這個樣子:
#<ActiveRecord::Relation [#<SubComponent id: 1, name: "Parent Sub", parent_sub_component_id: nil, parent_sub_component_name: nil created_at: "2017-07-07 00:29:37", updated_at: "2017-07-07 00:29:37">, #<SubComponent id: 2, name: "Child Sub", parent_sub_component_id: 1, parent_sub_component_name: "Parent Sub" created_at: "2017-07-07 00:29:37", updated_at: "2017-07-07 00:29:37">]>
你的意思是一個特定的父組件的每子,以及所有的子子,不管他們是在層次結構中有多深?如果不是,你能給我們一個你想達到的例子輸出嗎? –
子組件只會有一個父類,所以我希望得到的是父母的名字與它的ID一起。 – quicklikerabbit