Ferdinand Rosario
Ferdinand Rosario

Reputation: 147

has_many association Rails4.2

A rails newbie here, I'm created has_many assocation for category and product but getting error when checking the relationship in console

2.2.0 :004 > Category.last.products
  Category Load (0.6ms)  SELECT  "categories".* FROM "categories"  ORDER BY "categories"."id" DESC LIMIT 1
NoMethodError: undefined method `products' for nil:NilClass

I'm using Rails 4.2.0 with ruby 2.2.0

Category model

class Category < ActiveRecord::Base
  has_many :products
end

Product Model

class Product < ActiveRecord::Base
  belongs_to :category
end

Product Model

class CreateProducts < ActiveRecord::Migration
  def change
    create_table :products do |t|
      t.string :product_name
      t.float :price, precision: 5, scale: 2, default: 0.00
      t.boolean :is_available, default: true
      t.integer :category_id
      t.string :description
      t.integer :quantity

      t.timestamps null: false
    end
  end
end

Upvotes: 1

Views: 72

Answers (2)

Maxim Pontyushenko
Maxim Pontyushenko

Reputation: 3053

It looks like you don't have any Category object.

Category.last.products

NoMethodError: undefined method `products' for nil:NilClass

Upvotes: 0

Nermin
Nermin

Reputation: 6100

Problem is that you have no records in Category model.

When you call Category.last you get nil object because you have no records, and when you call products it gets called on nil object.

First create record in database, with Category.create then you can call Category.last and it will give you last record, then when products gets called it will be called on last category, and won't give you undefined method for nil object.

Upvotes: 4

Related Questions