。
这个错误是由于在Rails中使用scaffolding生成的代码中,对于has_many关联的模型,没有正确设置相关联的外键。下面是解决这个错误的步骤:
class Product < ApplicationRecord
has_many :comments
end
class CreateComments < ActiveRecord::Migration[6.0]
def change
create_table :comments do |t|
t.text :content
t.references :product, foreign_key: true
t.timestamps
end
end
end
dependent: :destroy
选项来解决该问题。例如:class CreateComments < ActiveRecord::Migration[6.0]
def change
create_table :comments do |t|
t.text :content
t.references :product, foreign_key: { to_table: :products, on_delete: :cascade }
t.timestamps
end
end
end
rails destroy scaffold Product
rails destroy scaffold Comment
rails generate scaffold Product name:string
rails generate scaffold Comment content:text product:references
这样重新生成的代码应该会正确设置关联关系。
关于Rails scafolding associations has_many错误的更详细的解释和解决方法,可以参考腾讯云的Rails开发文档:Rails开发文档。
领取专属 10元无门槛券
手把手带您无忧上云