RoR嵌套的optgroups

时间:2015-02-02 23:40:25

标签: ruby-on-rails grouped-collection-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表是共享相同pet_categories的pet_types的连接表。

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

由于

编辑:我设法获得宠物类型collection_select和宠物类别groups_collection_select一旦我更新了关系,现在第三个(宠物品种)是我坚持的..

1 个答案:

答案 0 :(得分:0)

我现在理解,经过一些研究后发现不可能有嵌套组但是肯定应该可以使用某种帮助器,但是由于缺乏更好的解决方案,我添加了PetTypeCategory模型: / p>

  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>

所以对于第三次选择而不是:

Dog
  Small
    Breed

我有:

Dog Small
  Breed
相关问题