首页 > 解决方案 > 如果散列具有 id,则将散列作为关联分配给对象失败,需要了解原因

问题描述

我有一个带有 id 的哈希,我想将其分配为与对象的关联,我收到此错误

{"amount"=>nil, "base_currency_amount"=>nil, "currency_id"=>1, "deal_product_id"=>nil, 
"expected_close"=>"2021-06-02", "id"=>3, "name"=>"test", "product_id"=>nil}

(byebug) new_record.deal = current_properties["deal"]
*** ActiveRecord::RecordNotFound Exception: Couldn't find LeadDeal with ID=3 for Lead 
with ID=

nil

但是当我从哈希中删除 id 时,它可以工作

(byebug) new_record.deal = current_properties["deal"].except("id")
{"amount"=>nil, "base_currency_amount"=>nil, "currency_id"=>1, "deal_product_id"=>nil, "expected_close"=>"2021-06-02", "name"=>"test", "product_id"=>nil}
(byebug) new_record.deal
#<LeadDeal id: nil, account_id: 1623836761, name: "test", amount: nil, expected_close: "2021-06-02", created_at: nil, updated_at: nil, deal_product_id: nil, currency_id: 1, base_currency_amount: nil, product_id: nil>

我认为这是因为 new_record 缺少 id,但即使我添加了 id,它也会失败并出现此错误

(byebug) new_record.id = 3
3
(byebug) new_record.company = current_properties["company"]
*** ActiveRecord::RecordNotFound Exception: Couldn't find LeadCompany with ID=3 for Lead with ID=3

nil

所有值都存在于 db 中,如果我只是从哈希中删除 id,它会按预期工作,我想知道为什么会发生这种情况

标签: ruby-on-railsruby

解决方案


推荐阅读