沿着我有一个子组件模型,它可以属于其他子组件。我的模型是这样的:在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