1
我有人幫我看看樹狀結構。我已成功創建了名爲「元素」的單個表之間的父子關聯。此外,條目以適當的方式保存。在rails上顯示樹狀結構
我已經構建了代碼,但它在一個層次上工作,因爲我已經使用了我想要優化的循環,所以希望看到代碼可以有快速解決方案。
class Element
include Mongoid::Document
validates :name, presence: true
field :name, type: String
field :description, type: String
field :top, type: String
has_many :media_files
has_and_belongs_to_many :parents, :class_name => 'Element'
has_and_belongs_to_many :childrens, :class_name => 'Element'
def self.js_tree
json_data = Array.new
elements = Element.where(top: "true")
get_inner_elements elements, json_data
return json_data.uniq {|e| e[:id] }.to_json
end
def self.get_inner_elements elements, json_data
elements.each do |element|
single_element element, json_data
element.childrens.each do |inner_element_one|
single_element inner_element_one, json_data, element.id
inner_element_one.childrens.each do |inner_element_two|
single_element inner_element_two, json_data, inner_element_one.id
inner_element_two.childrens.each do |inner_element_three|
single_element inner_element_three, json_data, inner_element_two.id
inner_element_three.childrens.each do |inner_element_four|
single_element inner_element_four, json_data, inner_element_three.id
end
end
end
end
end
return json_data
end
def self.single_element element, json_data, parent=nil
json_data << {
:id => "#{element.id}",
:parent => "#{parent.nil? ? '#' : parent}",
:a_attr=> { class: "foldor-icon" },
:text => "#{element.name}"
}
element.media_files.each do |mf|
json_data << {
:id => "file_#{element.id}_#{mf.id}",
:parent => "#{element.id}",
:text => mf.file_filename,
:icon => mf.icon,
}
end
return json_data
end
end
前端:
<script type="text/javascript">
data = $.parseJSON('<%= raw Element.js_tree %>')
$('#container').jstree({
'core' : {
'data' : data
}
});
</script>
的get_inner_elements需要進行優化,請任何人建議如何做到這一點有什麼遞歸需要使用我無法應用。
Thannks