如何在Rails 3的下拉列表中排列来自祖先树的条目? [英] How to arrange entries from Ancestry tree in dropdown list in Rails 3?

查看:31
本文介绍了如何在Rails 3的下拉列表中排列来自祖先树的条目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个下拉列表,其中填充了来自使用祖先的表中的数据.

我想排列列表中的数据,以便条目与他们的兄弟姐妹一起分组,并在他们的父母之下.

此代码有效,但未排列条目:<代码><%= builder.select("id", Location.all.collect {|l| [ l.name_nb, l.id ] }, { :include_blank => true }) %>

我试过这条线:<代码><%= builder.select("id", Location.arrange.collect {|l| [ l.name_nb, l.id ] }, { :include_blank => true }) %>然后我收到消息:#

的未定义方法 `name_nb'

我做错了什么?我该如何安排参赛作品?

解决方案

在我的应用程序中,我有 4 个深度级别的模型.这是我用于下拉列表的代码.

控制器:

before_filter :collection_for_parent_select, :except =>[:索引,:显示]def collection_for_parent_select@categories = ancestry_options(Category.unscoped.arrange(:order => 'name')) {|i|"#{'-' * i.depth} #{i.name}" }结尾def ancestry_options(items)结果 = []items.map 做 |item, sub_items|结果<<[产量(项目),项目.id]#这是一个递归调用:结果 += ancestry_options(sub_items) {|i|"#{'-' * i.depth} #{i.name}" }结尾结果结尾

查看,使用haml和formtastics:

= f.input :parent_id, :as =>:select, :collection =>@类别

附言我知道这不是有效的解决方案,但它有效.也看看祖先 wiki

I have a dropdown list which is populated with data from a table that is using ancestry.

I want to arrange the data in the list, so that the entries are grouped together with their siblings, and under their parents.

This code is working, but doesn't arrange the entries: <%= builder.select("id", Location.all.collect {|l| [ l.name_nb, l.id ] }, { :include_blank => true }) %>

I have tried this line: <%= builder.select("id", Location.arrange.collect {|l| [ l.name_nb, l.id ] }, { :include_blank => true }) %> Then I get the message: undefined method `name_nb' for #

What am I doing wrong? How can I arrange the entries?

解决方案

In my application i have 4 depth level model. This is a code that im use for dropdown.

Controller:

before_filter :collection_for_parent_select, :except => [:index, :show]

  def collection_for_parent_select
    @categories = ancestry_options(Category.unscoped.arrange(:order => 'name')) {|i| "#{'-' * i.depth} #{i.name}" }
  end

  def ancestry_options(items)
    result = []
    items.map do |item, sub_items|
      result << [yield(item), item.id]
      #this is a recursive call:
      result += ancestry_options(sub_items) {|i| "#{'-' * i.depth} #{i.name}" }
    end
    result
  end

View, with haml and formtastics:

= f.input :parent_id, :as => :select, :collection => @categories

P.S. I know this is not the efficient solution, but it works. Also take a look at ancestry wiki

这篇关于如何在Rails 3的下拉列表中排列来自祖先树的条目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆