2017-04-20 33 views
1

以下模型:的ActiveRecord :: AssociationTypeMismatch {}這是哈希(#70364214688040)的一個實例,使用 「CLASS_NAME」

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

在我的控制,我試圖建立一個新的實例:

@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"}}) 

以下PARAMS給我的錯誤

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 

但比我得到的失敗空白驗證。

如何修復模型以允許嵌套屬性?

回答

2

存在的問題是,您嘗試將散列傳遞給原作者和位置的作者方法,並且期望實例位置。

長話短說,只是檢查出accepts_nested_attributes_for

您所看到的驗證錯誤可能是一個沒有被滿足一個驗證。您可能要檢查貨物和定位對象的錯誤信息,例:@shipment.errors.messages

accepts_nested_attributes_for將增加origin_attributes=destination_attributes=作家方法,這將使事情的工作。您必須將您傳遞至new的散列鍵從origin更改爲origin_attributes,並將destination更改爲destination_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或相似。擁有屬性名稱的「位置」清楚地表明您正在談論地點,而不是其他事情。

+0

你是最棒的!謝謝! – user664859

相關問題