【问题标题】:Rails model relation MissingAttributeErrorRails 模型关系 MissingAttributeError
【发布时间】:2015-06-19 03:09:27
【问题描述】:

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

ActiveModel::MissingAttributeError(无法写入未知属性product_id): app/controllers/admin_controller.rb:27:in `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(无法写入未知属性product_id): app/controllers/admin_controller.rb:27:in `create_product'

我不知道发生了什么

有什么想法吗?

谢谢

【问题讨论】:

  • 由于错误来自 admin_controller,能否请您也包含该代码?
  • Feature 是 Category 和 Product 模型的连接吗?

标签: ruby-on-rails ruby ruby-on-rails-4 model ruby-on-rails-3.2


【解决方案1】:

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

ActiveModel::MissingAttributeError(无法写入未知属性product_id)

所以您没有 product_id 字段并查看您的关联和功能表迁移,您忘记在您的功能表中添加 product_id 字段。

修复:

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

rails g migration AddProductIdToFeatures product_id:integer
rake db:migrate

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-15
    • 1970-01-01
    • 2018-10-27
    • 2018-01-28
    相关资源
    最近更新 更多