1

私は3つのフィールドID名parent_category_idを持つテーブルカテゴリを持っています

カテゴリとサブカテゴリは両方とも、parent_category_id を持つ同じカテゴリ テーブルに格納されます

例:

id--------------名前-------------------parent_category_id

1-------------Category1-------------------nil

2------------ subCategory11----------------1

3------------サブカテゴリ12----------------1

4-------------Category2------------------nil

5--------------subCategory21---------------4

6 --------------subCategory22---------------4

このようなカテゴリモデルから選択ボックスを構築しようとしています

選択ボックス:

category1
    subcategory11
    subcategory12
category2
    subcategory21
    subcategory22

ユーザーはカテゴリ1またはサブカテゴリ11を選択できます

Rails3.2でそのようなドロップダウンボックスを作る方法

4

2 に答える 2

1

options_for_selectヘルパー メソッドを使用して、選択フィールドのカスタム オプションを作成できます : http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/options_for_select

渡すことができる配列を作成するための再帰的なメソッドは、次のoptions_for_selectようになります。

def subcat_prefix(depth)
  (" " * 4 * depth).html_safe
end

def category_options_array(categories=[], parent_id=nil, depth=0)
  Category.where(parent_category_id: parent_id).order(:id).each do |category|
    categories << [subcat_prefix(depth) + category.name, category.id]
    category_options_array(categories, category.id, depth+1)
  end

  categories
end

メソッドを使用するには、たとえば次のようにします。

select_tag :category_id, options_for_select(category_options_array)

これは、サブカテゴリのレベルがいくつであっても機能することに注意してください。選択フィールドの外観を変更するには、subcat_prefixメソッドを別の方法で定義するか、クラスと CSS を使用してオプション タグのスタイルを設定します。

于 2013-09-20T20:09:14.787 に答える
0

これには「awesome_nested_set」gem を使用します。その使用は非常にスムーズです。

宝石「awesome_nested_set」

parent_id を持つカテゴリ テーブルが既にある場合は、次の 3 つの列をテーブルに追加します。

add_column :categories, :lft, :integer
add_column :categories, :rgt, :integer
add_column :categories, :depth, :integer

parent_id の代わりにカスタムの parent(something_parent_id) id がある場合は、次のようにカスタムの parent_id のオプションとして渡します。

act_as_nested_set :parent_column => :parent_category_id

セレクトボックスとして使いたい場合

f.select :parent_id, nested_set_options(Category, @category) {|i| "#{'-' * i.level} #{i.name}" }

また

 select_tag 'parent_id', options_for_select(nested_set_options(Category) {|i| "#{'-' * i.level} #{i.name}" } )
于 2013-09-22T03:50:43.387 に答える