Luis Pereira
Luis Pereira

Reputation: 1521

Ruby ActiveModel::MissingAttributeError

I'm trying to learn on my own ruby database relations. I have a relation of 1 "Category" to many "Products" and I'm trying to add a product to the remote database (heroku server).

TIMESTAMP_create_products.rb

class CreateProducts < ActiveRecord::Migration
    def up
        create_table :products, primary_key: 'product_id' do |p|
            p.index :product_id
            p.string :name
            p.decimal :price
            p.references :categories, index: true
        end
    end

    def down
        drop_table :products
    end
end

TIMETSTAMP_create_categories.rb

class CreateCategories < ActiveRecord::Migration
    def up
        create_table :categories, primary_key: 'category_id' do |c|
      c.index :category_id
            c.string :name
            c.integer :parentId
        end
    end

    def down
        drop_table :categories
    end
end

model.rb

class Products < ActiveRecord::Base
  self.primary_key = "product_id"
    validates :name, presence: true, uniqueness: true
    belongs_to :categories, class_name: "Categories", foreign_key: 'category_id'
end

class Categories < ActiveRecord::Base
  self.primary_key = "category_id"
    validates :name, presence: true, uniqueness: true
    has_many :products, class_name: "Products"
end

I add manually a category to the database and every time I try to execute the code:

Products.create(name: "name1", price: "1.1", categories: Categories.find(1))

It gives me the output:

ActiveModel::MissingAttributeError can't write unknown attribute category_id

Is there anything missing here? I don't understand why this is not working.

Upvotes: 0

Views: 149

Answers (1)

haradwaith
haradwaith

Reputation: 2731

You may have a problem with singular / plural.

In your migration, to create the table products, you have the line:

p.references :categories, index: true

This should add to your table the column categories_id.

However, in the Products model, the foreign key is set to category_id. So when you try to attach a category to a production, it's trying to write the ID of the category to the column category_id of the table categories, which doesn't exists.

By changing the reference name in the products migration, everything should work fine:

create_table :products, primary_key: 'product_id' do |p|
  p.index :product_id
  p.string :name
  p.decimal :price
  p.references :category, index: true
end

Upvotes: 1

Related Questions