将多个数据添加到Has Many中的一个实体并属于关系



我正在处理一个表单,其中有一个用户可以选择主类别和子类别。但我希望他能够选择多个主要类别和子类别。

我设置了选择主类别,他可以选择多个类别。但子类别是不同的表,我想让他选择关于主类别的子类别,我不明白我该如何管理它。

当前我正在进行以下操作,它运行良好。

我的user.rb模块

has_and_belongs_to_many :categories

我的分类.rb型号

has_and_belongs_to_many :users

我已经创建了迁移来创建联接表

class CreateJoinTableUsersCategories < ActiveRecord::Migration[5.2]
def change
create_join_table :users, :categories do |t|
t.index [:user_id, :category_id]
t.index [:category_id, :user_id]
end
end
end

在我的控制器中

@categories = Category.find(params[:expertise])
@user.categories << @categories

这一切都很好,但我很困惑如何添加子类别,然后如何为子类别提供选择主类别的选项。我正在考虑以下解决方案。

  1. 我使用大的组合jquery框,在那里我可以选择主类别和子类别,然后保存它
  2. 我使用两个组合,所以第一个是主类别,它填充子类别,但我必须填充所有主类别子类别

知道我该怎么做吗?

如上所述,您需要的是自引用关联。https://guides.rubyonrails.org/association_basics.html#self-加入

class Category < ApplicationRecord
has_many :subcategories, class_name: "Category",
foreign_key: "parent_id"
belongs_to :parent, class_name: "Category", optional: true
belongs_to :user
end

这里是迁移:

class CreateCategories < ActiveRecord::Migration[5.0]
def change
create_table :categories do |t|
t.references :parent
t.references :user
t.timestamps
end
end
end

你现在可以做:

a = Category.create(name: "Animal")
b = Category.create(name: "Dog")
a.subcategories << b
a.save

相关内容

最新更新