I have some models in my application, and i'm trying to save data but i got an error:
ActiveModel::MissingAttributeError (can't write unknown attribute product_id
):
app/controllers/admin_controller.rb:27:in `create_product'
I have 3 models
Category model
class Category < ActiveRecord::Base
has_many :features
has_many :products
end
Migration:
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
Feature Model
class Feature < ActiveRecord::Base
has_and_belongs_to_many :categories
has_and_belongs_to_many :products
end
Migration
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
Product model
class Product < ActiveRecord::Base
belongs_to :category
has_many :features
end
Migration
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
I got this error when i try to save a product
ActiveModel::MissingAttributeError (can't write unknown attribute
product_id
): app/controllers/admin_controller.rb:27:in `create_product'
I cannot figure out what's happening
any ideas?
Thanks
If you look at your error, it clearly says
so you don't have a product_id field and looking at your associations and your features table migration, you forgot to add product_id field in your features table.
FIX:
To add product_id field in your features table you need to create a new migration and then migrate it to db: