在Rails 3中,要在下拉列表中安排Ancestry树中的条目,可以使用以下步骤:
gem 'ancestry'
然后运行bundle install
。
Category
的模型,请在app/models/category.rb
中添加以下代码:class Category< ActiveRecord::Base
has_ancestry
end
app/helpers/categories_helper.rb
中添加以下代码:module CategoriesHelper
def ancestry_select(categories, select_options = {})
select_options.reverse_merge!({
selected: nil,
disabled: nil,
include_blank: true,
prompt: "Select a category"
})
content_tag(:select, name: "category[parent_id]") do
options_for_select(
nested_options_for_select(categories, select_options),
select_options[:selected]
)
end
end
private
def nested_options_for_select(categories, select_options, level = 0)
result = []
categories.each do |category|
option = [("-" * level) + category.name, category.id]
if select_options[:disabled] && select_options[:disabled].include?(category)
option[0] = "[#{option[0]}]"
end
result<< option
if category.children.any?
result += nested_options_for_select(category.children, select_options, level + 1)
end
end
result
end
end
app/views/categories/_form.html.erb
中添加以下代码:<%= form_for(@category) do |f| %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :parent_id %><br />
<%= ancestry_select(Category.arrange) %>
</div>
<div class="actions">
<%= f.submit "Save" %>
</div>
<% end %>
现在,下拉列表应该显示Ancestry树中的条目。请注意,这个答案没有涉及到云计算相关的内容,因为Ancestry是一个基于Rails的树形数据结构插件,与云计算无关。
领取专属 10元无门槛券
手把手带您无忧上云