"Location" -6ren">
gpt4 book ai didi

ruby-on-rails - ActiveRecord::AssociationTypeMismatch {} 是 Hash 的一个实例(#70364214688040)

转载 作者:行者123 更新时间:2023-12-01 00:32:37 24 4
gpt4 key购买 nike

以下模型使用“class_name”:

class Shipment < ApplicationRecord
belongs_to :origin, :class_name => "Location"
belongs_to :destination,:class_name => "Location"
end

在我的 Controller 中,我正在尝试构建一个新实例:
@shipment = Shipment.new({
"origin" => {"name"=>"12312", "country"=>"US", "city"=>"Cambridge", "state"=>"MA", "postal_code"=>"02138", "address1"=>"Massachusetts Avenue, 1234", "address2"=>"123213"},
"destination" => {"name"=>"12312", "country"=>"US", "city"=>"Cambridge", "state"=>"MA", "postal_code"=>"02138", "address1"=>"Massachusetts Avenue, 1234", "address2"=>"123213"}})

以下参数给了我错误
ActiveRecord::AssociationTypeMismatch: Location(#70364217448000) expected, got {"name"=>"12312", "country"=>"US", "city"=>"Cambridge", "state"=>"MA", "postal_code"=>"02138", "address1"=>"Massachusetts Avenue, 1234", "address2"=>"123213"} which is an instance of Hash(#70364214688040)

为了绕过这个,我正在使用这个:
@shipment = Shipment.new
@shipment.build_origin {"name"=>"12312", "country"=>"US", "city"=>"Cambridge", "state"=>"MA", "postal_code"=>"02138", "address1"=>"Massachusetts Avenue, 1234", "address2"=>"123213"}
@shipment.build_destination {"name"=>"12312", "country"=>"US", "city"=>"Cambridge", "state"=>"MA", "postal_code"=>"02138", "address1"=>"Massachusetts Avenue, 1234", "address2"=>"123213"}

然后,我尝试在模型中包含以下内容:
accepts_nested_attributes_for :origin
accepts_nested_attributes_for :destination

但是我得到了一个失败的空白验证。

如何修复模型以允许嵌套属性?

最佳答案

问题在于您试图将散列传递给作者方法以获取原点和位置,并且它需要一个实例位置。

长话短说,只需查看 accepts_nested_attributes_for

您看到的验证错误可能是一种未满足的验证。您可能需要检查货件和位置对象的错误消息,例如:@shipment.errors.messagesaccepts_nested_attributes_for将添加 origin_attributes=destination_attributes=作家方法,这将使事情发挥作用。您必须更改传递给 new 的哈希键来自 originorigin_attributes , 和 destinationdestination_attributes .

class Shipment < ApplicationRecord
belongs_to :origin, class_name: 'Location'
belongs_to :destination, class_name: 'Location'

accepts_nested_attributes_for :origin, :destination
end

然后你可以使用:
@shipment = Shipment.new({
"origin_attributes" => {
"name" => "12312", "country" => "US", "city" => "Cambridge", "state" => "MA", "postal_code" => "02138", "address1" => "Massachusetts Avenue, 1234", "address2" => "123213"
},
"destination_attributes" => {
"name" => "12312", "country" => "US", "city" => "Cambridge", "state" => "MA", "postal_code" => "02138", "address1" => "Massachusetts Avenue, 1234", "address2" => "123213"
}
})

作为一个完全不相关的旁注,我将这些属性称为 source_locationdestination_location或类似。属性名称上的“位置”清楚地表明您在谈论位置,而不是其他事物。

关于ruby-on-rails - ActiveRecord::AssociationTypeMismatch {} 是 Hash 的一个实例(#70364214688040),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43531470/

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