【问题标题】:best way to share has_and_belongs_to_many between multiple moles rails在多个鼹鼠导轨之间共享 has_and_belongs_to_many 的最佳方式
【发布时间】:2020-05-11 06:48:19
【问题描述】:

所以目前我有一个类别和一个文章模型:

class Article < ApplicationRecord
  has_and_belongs_to_many :categories
end

class Category < ApplicationRecord
end

效果很好。但现在我想扩展系统并引入其他模型,这些模型也将以类似的方式分配类别,例如:

class Article < ApplicationRecord
  has_and_belongs_to_many :categories
end

class Project < ApplicationRecord
  has_and_belongs_to_many :categories
end

我想知道,与其为每个模型创建新的连接表,是否可以共享一个连接表?或者这实际上是更可取的方法,如果是,为什么?

【问题讨论】:

  • 我还是会选择单独的桌子。连接表只有两列,不使用多态关联会给你真正的外键约束、更好的连接等。

标签: ruby-on-rails database-design database-migration rails-migrations


【解决方案1】:

使用polymorphic associations。但这不适用于has_and_belongs_to_many,因此我们需要手动设置多对多关系。见this answer for more

class Category < ApplicationRecord
  has_many :category_relations
end

class CategoryRelation < ApplicationRecord
  belongs_to :categories
  belongs_to :categorable, polymorphic: true
end

class Article < ApplicationRecord
  has_many :category_relations, as: categorable
  has_many :categories, through: :category_relations
end

class Project < ApplicationRecord
  has_many :category_relations, as: categorable
  has_many :categories, through: :category_relations
end

迁移看起来像......

class CreateCategorable < ActiveRecord::Migration[5.2]
  def change
    create_table :categories do |t|
      t.string :name
      t.timestamps
    end

    create_table :categories_relations, id: false do |t|
      t.references :categories, index: true
      t.references :categorable, polymorphic: true, index: true
    end
  end
end

t.references :categorable, polymorphic: true, index: true 是一种方便的方法,它设置t.bigint :categorable_idt.string :categorable_type 来存储关系的ID 和类。 categorable_type: 'Article', categorable_id: 5 引用 ID 为 5 的文章。

由于是多对多,无需修改articlesprojects 表。

多态关联很方便,但是因为它不使用外键,所以数据库不能强制引用完整性。这是由 Rails 处理的。这在 Rails 应用程序中是可以接受的,因为数据库通常只由 Rails 模型控制。 Rails 模型和数据库可以视为一个单元。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-06
    • 1970-01-01
    • 2013-08-24
    • 2016-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多