我有 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)
uj5u.com熱心網友回復:
在您的模型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
uj5u.com熱心網友回復:
請遵循正確的命名約定
這篇文章可能會有所幫助 - https://www.bigbinary.com/learn-rubyonrails-book/summarizing-rails-naming-conventions
在 ServiceBrand 模型中
class ServiceBrand < ApplicationRecord
belongs_to :brand, class_name: 'ServiceBrandDetail'
end
belongs_to 應該是外鍵名稱,即你的品牌
您可以從代碼庫中洗掉現有模型和表,然后嘗試以下一種。(我測驗過)
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
然后嘗試創建您在問題中嘗試過的模型物件。它會作業????
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/487399.html
標籤:轨道上的红宝石
