js111
js111

Reputation: 1314

Rails "AssociationTypeMismatch" Error

In attempts to test my models, im trying to run the following in rails console:

user.occasions << Occasion.first

getting this error:

irb(main):013:0>  user.occasions << Occasion.first
Occasion Load (0.2ms)  SELECT "occasions".* FROM "occasions" LIMIT 1
(0.0ms)  begin transaction
(0.0ms)  rollback transaction
ActiveRecord::AssociationTypeMismatch: Occasion(#70119208170580) expected, got NilClass(#70119200119960)`

Here are my model classes:

class User < ActiveRecord::Base
  has_many :occasions
  rolify
  devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable
  attr_accessible :name, :email, :password, :password_confirmation, :remember_me, :id
end

class Occasion < ActiveRecord::Base
  attr_accessible :date, :name
  belongs_to :user
end

How can I get my code fragment to work?

Upvotes: 0

Views: 1718

Answers (1)

Kevin Bedell
Kevin Bedell

Reputation: 13424

It looks as if either:

  • You're attempting to add your first Occasion record to this User -- and there are no Occasion record yet created, or
  • You're attempting to add the first Occasion record to this User, and that record already belongs to another User.

Can you try this in the console and post the results?

foo = Occasion.first
Occasion.first.inspect

Upvotes: 4

Related Questions