Rails has_many_through

Rails has_many_through

我正在尝试设置一个 Rails 应用程序,其中包含按类型和子类型分类的记录;一个类型将有多个子类型,每个子类型将有许多记录。如果有任何关联,删除类型或子类型应该会失败。我原以为这可能有效,但我发现尝试 record.typetype.records.count 之类的东西不会 return 任何东西。这是设置:

class Type < ApplicationRecord
    has_many :subtypes, dependent: :restrict_with_exception
    has_many :records, through: :subtypes, dependent: :restrict_with_exception
end

class SubType < ApplicationRecord
   belongs_to :type
   has_many :records, dependent: :restrict_with_exception
end

class Record < ApplicationRecord
   has_one :subtype
   has_one :type, through: :subtype
end

然后,一些迁移​​将相关字段添加到已经存在的 类:

class LinkTypesSubtypesAndRecords < ActiveRecord::Migration[5.2]
    def change
        add_reference :subtypes, :record, index: true
        add_reference :subtypes, :type, index: true
        add_reference :records, :subtype, index: true
        add_reference :types, :subtype, index: true
    end
end

我在这里遗漏了什么吗?

在你的迁移中你应该添加引用

  1. subtype records table
  2. subtypes type table

因此迁移应该如下所示:

class LinkTypesSubtypesAndRecords < ActiveRecord::Migration[5.2]
    def change
        add_reference :records, :subtype, index: true
        add_reference :subtypes, :type, index: true
    end
end

更多信息here

更新 1

在您的模型中:

class Record < ApplicationRecord
  belongs_to :subtype

  delegate :type, :to => :subtype, :allow_nil => true
end