ruby 为相关记录创建一个表结构,以便于在控制器操作中使用

qrjkbowd  于 2023-03-17  发布在  Ruby
关注(0)|答案(2)|浏览(98)

我想建立一个任务和标签表。这是一个多对多的关联,所以一个任务可以有许多标签和标签可以附加到许多任务。
我是这样做的:

任务

class CreateTasks < ActiveRecord::Migration[7.0]
  def change
    create_table :tasks do |t|
      t.string :name
      t.text :note
      t.date :due_date
      t.boolean :finished, default: false
      t.references :tag, null: true, foreign_key: true

      t.timestamps
    end
  end
end

标签

class CreateTags < ActiveRecord::Migration[7.0]
  def change
    create_table :tags do |t|
      t.string :name
      t.string :slug
      t.references :task, null: true, foreign_key: true

      t.timestamps
    end
  end
end

标记任务

class CreateTaggedTasks < ActiveRecord::Migration[7.0]
  def change
    create_table :tagged_tasks do |t|
      t.references :task, null: false, foreign_key: true
      t.references :tag, null: false, foreign_key: true

      t.timestamps
    end
  end
end

注意:我添加了null: true,因为任务可以没有标记,标记也可以没有关联的任务
我的问题是:
在控制器中实现此功能的正确方法是什么?
我的想法是,既然一个任务可以被标记或不被标记,当我创建一个任务时,我会检查它是否被传递了一个或多个标记,并为每个标记创建一个tagged_task,如果没有,就创建一个简单的task
但我不确定这是不是最干净的方式。所以欢迎大家提出任何想法。谢谢!

r9f1avp5

r9f1avp51#

根据Rails文档,对于多对多关联,每个表的models如下所示:

class Task < ApplicationRecord
  has_many :tagged_tasks
  has_many :tags, through: :tagged_tasks
end

class TaggedTask < ApplicationRecord
  belongs_to :task
  belongs_to :tag
end

class Tag < ApplicationRecord
  has_many :tagged_tasks
  has_many :tasks, through: :tagged_tasks
end
chhkpiq4

chhkpiq42#

从您的问题中我可以看出,您正在寻找accepts_nested_attributes_for特性集-这是您在创建“基本”记录的同时创建相关记录时在控制器操作等方面使用的魔法。https://guides.rubyonrails.org/form_helpers.html#configuring-the-model,不过您也可能希望单击查看参考文档:https://api.rubyonrails.org/v7.0.4.2/classes/ActiveRecord/NestedAttributes/ClassMethods.html#method-i-accepts_nested_attributes_for
您还可以通过一个简单的连接表查看典型的“多对多”关联,并且可以在模型中使用has_and_belongs_to_many关系。https://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association
干杯!

相关问题