2017-04-18 113 views
1

我搭建了一個簡單示例來說明我遇到的問題。 在這個例子中,我有一個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) 

我看到我的飛行員被作爲哈希字符串發送,但我似乎沒有發現我應該如何去做,否則。

+2

你不能傳遞一個對象到像這樣的params散列。您可以嘗試發送該對象的'id',然後在目標中找到該對象。 –

回答

4

使用集合選擇並返回試驗編號。

<%= f.collection_select(:pilot_id, Pilot.all, :id, :name) %> 

注意,您需要更改starship_params

def starship_params 
    params.require(:starship).permit(:name, :pilot_id) 
    end 

添加attr_accessor爲:pilot_id

class Starship < ApplicationRecord 
    attr_accessor :pilot_id 

修改創建如下...

def create 
    @starship = Starship.new(starship_params) 
    @starship.pilot = Pilot.find(@starship.pilot_id) 
    respond_to do |format| 
    ... 
+0

我試過這個,但是現在我得到這個錯誤'undefined method' pilot_id'for#你的意思是? pilot'。任何我可能犯了錯誤的想法? – LRP

+0

啊,對,對不起,這是'has_one'。答覆修改。歡呼聲 – SteveTurczyn

+0

完全謝謝你的作品 – LRP

0

你有一對一的操作關係。只列出所有飛行員可以覆蓋他們。創建一個新的飛行員比從整個名單中分配一個更好。

如果您想使用此代碼,請繼續操作。請記住,如果您想轉移飛行員,也可以使用下面的Pilot.pluck(:id)

<div class="field"> 
    <%= f.label :pilot_id %> 
    <%= f.select :pilot_id, Pilot.where('starship_id is NULL').pluck(:id) %> 
</div> 

現在,在您starship_controller創建方法 寫

def create 
    @starship = Starship.new(starship_params) 
    pilot = @starship.build_pilot 
    pilot.id= params[:starship][:pilot_id] 
    pilot.reload 
    respond_to do |format| 
     if @starship.save 
     format.html { redirect_to root_path, notice: 'Starship successfully created.' } 
     else 
     format.html { redirect_to root_path, notice: 'Error occured.' } 
     end 
end 

你強PARAMS應該

def starship_params 
    params.require(:starship).permit(:name, :pilot_id) 
end 

希望這有助於...

+0

我得到了'沒有身份證找不到飛行員'。我試着用'f.select:pilot'和'params.require(:starship).permit(:name,:pilot)'來取代原來的錯誤 – LRP

0

只需更換下面的代碼與您的代碼你很好走。

<%= f.label :pilot %> 
<%= f.select :pilot, Pilot.all.map{ |p| [p.name, p.id] } %> 

這將在選擇下拉顯示飛行員的名字,並保存特定飛行員的ID,同時節省。

+0

但是現在仍然有同樣的錯誤, 「name」=>「Nostromo」,「pilot」=>「2」}' – LRP

相關問題