user984621
user984621

Reputation: 48443

Ruby - undefined method `empty?' for nil:NilClass

More than 3 hours I am trying to solve pretty easy error (on the first glance):

undefined method `empty?' for nil:NilClass

but still no success.

I have the DB table products, which contains the columns category_id and manufacturer_id.

Associations:

class Product < ActiveRecord::Base
  belongs_to :manufacturer
  belongs_to :category
  ...
end
class Category < ActiveRecord::Base # the same for Manufacturer
  has_ancestry
  has_many :products

end

Trying to grab some data:

Product.where('category_id IS NOT NULL AND manufacturer_id IS NOT NULL').each do |product|
  ...
  puts product.manufacturer.name # here's the error
  puts product.category.name # here's the error
  ...
end

I fetched all rows, where is not NIL value in the columns manufacturer_id and category_id... so how can I get this error?

Also, I've tried:

 ...
  puts product.manufacturer.name unless product.manufacturer_id.nil?
  puts product.category.name unless product.category_id.nil?
  ...

What am I doing wrong?

Upvotes: 0

Views: 3866

Answers (2)

Paulo Henrique
Paulo Henrique

Reputation: 1025

Problably is a business logic problem on your database considering your query.

IMHO u are calling some objects that will not be valid ones. Check your database to see if all registers attend your validations logic.

Upvotes: 0

Tom L
Tom L

Reputation: 3409

You most likely deleted a manufacturer or category so there's no corresponding record to match the foreign key.

Upvotes: 1

Related Questions