gpt4 book ai didi

ruby-on-rails-3 - Ruby On Rails 3.2.1 中的 ActiveRecord::AssociationTypeMismatch

转载 作者:行者123 更新时间:2023-12-04 07:05:58 28 4
gpt4 key购买 nike

我对 Ruby On Rails 3.2.1 进行了一些小测试,这是对我的模型的解释:

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

class Task < ActiveRecord::Base
belongs_to :project
end

但是当我尝试为我的项目保存任务时出现错误:

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>'

请帮帮我。为什么会引发此异常?

最佳答案

Task.first.id 和 Task.last.id 返回 Fixnum 类型的数字您不能将期望类 Task 的 Project.first.tasks 分配给数字数组。

关于ruby-on-rails-3 - Ruby On Rails 3.2.1 中的 ActiveRecord::AssociationTypeMismatch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9722685/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com