我搭建了一個簡單示例來說明我遇到的問題。 在這個例子中,我有一個Starship和一個Pilot。我希望能夠在創作時將現有的飛行員分配給星艦。模型(#...)預期,使用選擇標記時出現String(#...)錯誤
starship.rb
class Starship < ApplicationRecord
has_one :pilot
validates :name, presence: true
end
pilot.rb
class Pilot < ApplicationRecord
belongs_to :starship, optional: true
validates :name, presence: true
end
飛船/ _form.html.erb
<div class="field">
<%= f.label :pilot %>
<%= f.select :pilot, Pilot.all %>
</div>
starships_controller.rb
def starship_params
params.require(:starship).permit(:name, :pilot)
end
PARAMS哈希
{"name"=>"Nostromo", "pilot"=>"#<Pilot:0x007f85ff547f90>"}
而且我得到這個錯誤
Pilot(#70106745549840) expected, got String(#70106709663840)
我看到我的飛行員被作爲哈希字符串發送,但我似乎沒有發現我應該如何去做,否則。
你不能傳遞一個對象到像這樣的params散列。您可以嘗試發送該對象的'id',然後在目標中找到該對象。 –