ActiveRecord :: AssociationTypeMismatch in Ruby On Rails 3.2.1

I have a little test for Ruby On Rails 3.2.1 Here is an 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 got an 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 is this exception being thrown?

+3


source to share


1 answer


Task.first.id and Task.last.id return the number of Fixnum types. You cannot assign Project.first.tasks that expect a Task class to an array of numbers.



+3


source







All Articles