将多个数据添加到具有多个且属于关系的实体中

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

我已设置选择主要类别,他可以在其中选择多个类别。但是子类别是不同的表,我想给他选择相对于主要类别的子类别,我不知道该如何管理。

当前我正在关注,并且工作正常。

我的user.rb模型

  has_and_belongs_to_many :categories

我的category.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. 我使用两个组合,所以第一个是主类别,它填充子类别,但是我必须填充所有主类别子类别。

任何想法我该怎么做。

happy_moto 回答:将多个数据添加到具有多个且属于关系的实体中

如此处所述,您需要的是自我参照关联。 https://guides.rubyonrails.org/association_basics.html#self-joins

class Category < ApplicationRecord
  has_many :subcategories,class_name: "Category",foreign_key: "parent_id"

  belongs_to :parent,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
本文链接:https://www.f2er.com/3119612.html

大家都在问