Deekor
Deekor

Reputation: 9499

undefined method `[]' for nil:NilClass when creating a new object

So ive searched and can't find a existing question that has helped me with this.

I have a model:

class ClassComments < ActiveRecord::Base
 # attr_accessible :title, :body
 belongs_to :user
 belongs_to :class, :class_name => 'Clas'
end

And when I call c = ClassComments.new in my controller I get this error:

undefined method `[]' for nil:NilClass

Any ideas on what is causing this? I'm stumped!

Upvotes: 0

Views: 285

Answers (2)

Jay Truluck
Jay Truluck

Reputation: 1519

Changing the class name to something other than Clas or Class will fix the issue since class it is a reserved word in ruby/rails.

Source: http://latheesh.com/2010/02/02/rails-reserved-words/

Upvotes: 1

sq1020
sq1020

Reputation: 1090

I think you need to specify the foreign key in addition to the class name as in this question

So in your case, it would probably be:

belongs_to :class, :class_name => 'Clas', :foreign_key => "clas_id"

Upvotes: 0

Related Questions