Rails 模型关系 MissingAttributeError

Rails model relation MissingAttributeError

我的应用程序中有一些模型,我正在尝试保存数据但出现错误:

ActiveModel::MissingAttributeError(无法写入未知属性product_id): app/controllers/admin_controller.rb:27:在`create_product'

我有3个模型

类别模型

class Category < ActiveRecord::Base
    has_many :features
    has_many :products
end

迁移:

class CreateCategories < ActiveRecord::Migration
   def change
     create_table :categories do |t|
     t.string :name, null: false
     t.boolean :active, null: false, default: false 
     t.timestamps null: false
   end
end

特征模型

class Feature < ActiveRecord::Base
    has_and_belongs_to_many :categories
    has_and_belongs_to_many :products
 end

迁移

class CreateFeatures < ActiveRecord::Migration
   def change
      create_table :features do |t|
      t.belongs_to :category, index:true
      t.string :name, null: false
      t.timestamps null: false
   end
 end

产品型号

class Product < ActiveRecord::Base
    belongs_to :category
    has_many :features 
end

迁移

class CreateProducts < ActiveRecord::Migration
   def change
      create_table :products do |t|
      t.belongs_to :category, index:true
      t.string :name, null: false
      t.text :rating, null: false
      t.timestamps null: false
    end
 end

我在尝试保存产品时遇到此错误

ActiveModel::MissingAttributeError (can't write unknown attribute product_id): app/controllers/admin_controller.rb:27:in `create_product'

我不知道发生了什么

有什么想法吗?

谢谢

如果你看看你的错误,它清楚地说

ActiveModel::MissingAttributeError (can't write unknown attribute product_id)

所以您没有 product_id 字段并查看您的关联和功能 table 迁移,您忘记添加 product_id 字段中的特征 table.

修复:

要在您的功能中添加 product_id 字段 table 您需要创建一个新的迁移,然后将其迁移到 db:

rails g migration AddProductIdToFeatures product_id:integer
rake db:migrate