ka8725
ka8725

Reputation: 2918

ActiveRecord::AssociationTypeMismatch in Ruby On Rails 3.2.1

I have some little test for Ruby On Rails 3.2.1 Here is explanation for my models:

class Project < ActiveRecord::Base
  has_many :tasks
  accepts_nested_attributes_for :tasks
end

class Task < ActiveRecord::Base
  belongs_to :project
end

But when I tried to save tasks for my project I get error:

irb(main):037:0> Project.first.tasks = [Task.first.id, Task.last.id]
Project Load (0.2ms)  SELECT "projects".* FROM "projects" LIMIT 1
Task Load (0.1ms)  SELECT "tasks".* FROM "tasks" LIMIT 1
Task Load (0.1ms)  SELECT "tasks".* FROM "tasks" ORDER BY "tasks"."id" DESC LIMIT 1
ActiveRecord::AssociationTypeMismatch: Task(#70101178643360) expected, got Fixnum(#70101143633040)
from /Users/ka8725/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/activerecord-3.2.1/lib/active_record/associations/association.rb:204:in `raise_on_type_mismatch'
from /Users/ka8725/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/activerecord-3.2.1/lib/active_record/associations/collection_association.rb:308:in `block in replace'
from /Users/ka8725/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/activerecord-3.2.1/lib/active_record/associations/collection_association.rb:308:in `each'
from /Users/ka8725/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/activerecord-3.2.1/lib/active_record/associations/collection_association.rb:308:in `replace'
from /Users/ka8725/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/activerecord-3.2.1/lib/active_record/associations/collection_association.rb:41:in `writer'
from /Users/ka8725/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/activerecord-3.2.1/lib/active_record/associations/builder/association.rb:51:in `block in define_writers'
from (irb):37
from /Users/ka8725/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/railties-3.2.1/lib/rails/commands/console.rb:47:in `start'
from /Users/ka8725/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/railties-3.2.1/lib/rails/commands/console.rb:8:in `start'
from /Users/ka8725/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/railties-3.2.1/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'

Please, help me. Why does this exception raise?

Upvotes: 3

Views: 1627

Answers (1)

Ethan
Ethan

Reputation: 1616

Task.first.id and Task.last.id returns number of Fixnum type You cannot assign Project.first.tasks which expect class Task to an array of number.

Upvotes: 3

Related Questions