0

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

现在我有以下模型:

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 的连接表。

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

谢谢

编辑:一旦我更新了关系,我设法完成了宠物类型 collection_select 和宠物类别 grouped_collection_select,现在第三个(宠物品种)是我所坚持的。

4

1 回答 1

0

经过一番研究,我现在明白,虽然肯定不可能有嵌套组,但应该可以使用某种帮助程序,但是由于缺乏更好的解决方案,我添加到 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>

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

Dog
  Small
    Breed

我有:

Dog Small
  Breed
于 2015-02-04T17:34:42.353 回答