RoR 嵌套 optgroups

RoR nested optgroups

我已经在我的应用程序中成功实现了城市和区域模型的动态 select 菜单。

现在我有以下型号:

class Pet < ActiveRecord::Base
  belongs_to :pet_type
  belongs_to :pet_category
  belongs_to :pet_breed
end

class PetType < ActiveRecord::Base
  has_many :pet_categories, through: :pet_type_categories
  has_many :pet_type_categories
end

class PetCategory < ActiveRecord::Base
  has_many :pet_types, through: :pet_type_categories
  has_one :pet_type_category
end

class PetTypeCategory < ActiveRecord::Base
  belongs_to :pet_type
  belongs_to :pet_category
  has_many :pet_breeds
end

class PetBreed < ActiveRecord::Base
  belongs_to :pet_type_category
  belongs_to :pet_Type
  belongs_to :pet_category
end

迁移:

class CreatePetTypes < ActiveRecord::Migration
  def change
    create_table :pet_types do |t|
      t.string :name

      t.timestamps
    end
  end
end

class CreatePetCategories < ActiveRecord::Migration
  def change
    create_table :pet_categories do |t|
      t.string :name

      t.timestamps
    end
  end
end

class CreatePetTypeCategories < ActiveRecord::Migration
  def change
    create_table :pet_type_categories do |t|
      t.references :pet_type, index: true
      t.references :pet_category, index: true

      t.timestamps
    end
  end
end

class CreatePetBreeds < ActiveRecord::Migration
  def change
    create_table :pet_breeds do |t|
      t.string :name
      t.references :pet_type_category, index: true

      t.timestamps
    end
  end
end

pet_type_category table 是 pet_types 的联接 table,它们共享相同的 pet_categories。

所以我的问题是如何在创建表单中创建 pet_type、pet_category 和 pet_breed 的 3 个动态 select 菜单?

谢谢

编辑:更新关系后,我设法将宠物类型 collection_select 和宠物类别分组_collection_select 完成,现在第三个(宠物品种)是我遇到的问题..

经过一些研究,我现在明白不可能有嵌套组,但肯定可以使用某种帮助程序,但是由于缺乏更好的解决方案,我将其添加到 PetTypeCategory 模型中:

  def pet_type_category_names
    "#{self.pet_type.name} #{self.pet_category.name}"   
  end 

在我看来,现在我有:

<div class="field">
  <%= f.collection_select :pet_type_id, PetType.all, :id, :name, {prompt: "Choose your pet's type"} %>
</div>

<div class="field">
  <%= f.grouped_collection_select :pet_category_id, PetType.all, :pet_categories, :name, :id, :name, {prompt: "Choose your pet's category"} %>
</div>

<div class="field">
  <%= f.grouped_collection_select :pet_breed_id, PetTypeCategory.all, :pet_breeds, :pet_type_category_names, :id, :name, {prompt: "Choose your pet's breed"} %>
</div>

所以第 3 个 select 而不是:

Dog
  Small
    Breed

我有:

Dog Small
  Breed