rails - 无法在 RoR 的关联模型中保存数据

rails - can't save data in associated models in RoR

我有 2 个模型与关联 has_many 以及它们之间的级联 属性。

class ServicesBrandDetail < ApplicationRecord
    has_many :services_brands, foreign_key: "brand_id", dependent: :delete_all
end


class ServicesBrand < ApplicationRecord
  belongs_to :services_brand_details, foreign_key: "brand_id", 
end

Migration for both files

class CreateServicesBrandDetails < ActiveRecord::Migration[6.1]
  def change
    create_table :services_brand_details do |t|
      t.string :brand
      t.string :mail_list
      t.string :cc_list

      t.timestamps
    end
  end
end

class CreateServicesBrands < ActiveRecord::Migration[6.1]
  def change
    create_table :services_brands do |t|
      t.string :warehouse
      t.references :brand, null: false, foreign_key: {to_table: :services_brand_details}

      t.timestamps
    end
  end
end

现在我能够从 ServicesBrandDetails 模型创建和保存数据。但问题是当我从 ServiceBrand 创建记录时,它完美地创建了记录,但我无法将数据存储在数据库中。

record = ServicesBrandDetail.create(:brand => "a", :mail_list => 'abc@mail.com', :cc_list => 'def@mail.com')
record.save

Record successfully stored in DB.

child = record.services_brands.new(:warehouse => "in") <-- record was created successfully.
child.save

it give me error

C:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/activerecord-6.1.5/lib/active_record/inheritance.rb:237:in `compute_type': uninitialized constant ServicesBrand::ServicesBrandDetails (NameError)

在您的模型 ServicesBrand 中,您必须为 belongs_to

使用单数关联名称

将此 belongs_to :services_brand_details 更改为此 belongs_to :services_brand_detail

class ServicesBrand < ApplicationRecord
  belongs_to :services_brand_detail, foreign_key: "brand_id"
end

请遵循正确的命名约定

这篇文章可能会有所帮助 - https://www.bigbinary.com/learn-rubyonrails-book/summarizing-rails-naming-conventions

在服务品牌模型中

class ServiceBrand < ApplicationRecord
  belongs_to :brand, class_name: 'ServiceBrandDetail'
end

belongs_to 应该是外键名称,即 brand 在你的情况下

您可以从您的代码库中删除现有的模型和表格,然后尝试下面的一个。 (我测试过)

class ServiceBrandDetail < ApplicationRecord
  has_many :service_brands, foreign_key: :brand_id, dependent: :delete_all
end


class ServiceBrand < ApplicationRecord
  belongs_to :brand, class_name: 'ServiceBrandDetail'
end


Migration for both files

class CreateServiceBrandDetails < ActiveRecord::Migration[6.1]
  def change
    create_table :service_brand_details do |t|
      t.string :brand
      t.string :mail_list
      t.string :cc_list

      t.timestamps
    end
  end
end

class CreateServiceBrands < ActiveRecord::Migration[6.1]
  def change
    create_table :service_brands do |t|
      t.string :warehouse
      t.references :brand, null: false, foreign_key: {to_table: :service_brand_details}

      t.timestamps
    end
  end
end

然后尝试创建您在问题中尝试过的模型对象。它会起作用