Rails has_many_through

时间:2019-02-18 10:51:48

标签: ruby-on-rails rails-activerecord

我正在尝试建立一个Rails应用程序,该应用程序具有按类型和子类型分类的Records;一个类型将具有多个子类型,每个子类型将具有许多记录。如果有任何关联的类型,则删除类型或子类型将失败。我以为这可能有效,但是我发现尝试使用record.typetype.records.count之类的方法不会返回任何内容。设置如下:

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 个答案:

答案 0 :(得分:1)

在迁移中,您应该添加参考

    subtype表中records
  1. type表中subtypes

因此迁移应如下所示:

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