2013-03-27 30 views
2

我已經看到類似這樣的多個問題,但都沒有爲我工作。欄杆對象預期得到字符串

我有一個團隊模式:

class Team < ActiveRecord::Base 
    has_one :p1, :class_name => "Player", :foreign_key => 'player_id', :validate => true 
    has_one :p2, :class_name => "Player", :foreign_key => 'player_id', :validate => true 
end 

在我的團隊的_form.html.erb,我指的是球員

<%= f.collection_select :p1, Player.all, :id, :name %> 

然而,在表單提交,我看到的錯誤:

Player(#28401456) expected, got String(#14111904) 

Application Trace | Framework Trace | Full Trace 
app/controllers/teams_controller.rb:47:in `new' 

Parameters: 
{"utf8"=>"✓", 
"authenticity_token"=>"GSIcEvROFnvgGWT4HvE2VNqRw4NxU1J8iAw/WhZeRLk=", 
"team"=>{"p1"=>"1"}, 
"commit"=>"Create Team"} 

這裏是線

def create 
    @team = Team.new(params[:team]) 
    ..... 
end 

任何想法的代碼嗎?

回答

5

最後,工作:

<%= f.collection_select :p1_id, Player.all, :id, :name %> 

這裏是魔法: 我的遷移有t.references P1並在數據庫中創建p1_id列。 當表單提交,軌道正在尋找在參考的ID填寫:

def create 
    @team = Team.new(params[:team]) 
    ..... 
end 
+1

感謝這 - 非常誤導性的錯誤信息 - 應該告訴我們列名不匹配,並且將是一個20秒的修復,而不是一個小時 – JosephK 2015-11-17 19:13:03

+0

對此不能感謝。這也適用於鐵軌5的強烈參數。 – 2017-04-22 16:50:09

0

試試這個:

<%= f.collection_select :player_id, Player.all, :id, :name %> 
+0

嗯,我看到下列錯誤:NoMethodError在團隊#新 顯示曲目/應用/視圖/團隊/ _form.html.erb其中行#14提出: 未定義的方法'合併」爲:名稱:符號 提取的源(圍繞線#14): 11:

12:<% end %> 13: 14:<% = f.collection_select:p1,:player_id,Player.all,:id,:name%> 15:<! - <%= f.select:p1,Player.all.collect {| e | [e.name,e.id]}%> - > 16: 17:
Kiran 2013-03-27 20:09:27

0

我可能是錯的,但我的猜測是不是

<%= f.collection_select :p1, Player.all, :id, :name %> 

你需要

<%= f.collection_select :p1, :team_id, Player.all, :id, :name %> 

http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-collection_select

+0

I see the error: NoMethodError in Teams#new Showing track/app/views/teams/_form.html.erb where line #14 raised: undefined method 'merge' for :name:Symbol Extracted source (around line #14): 11:

12:<% end %> 13:14:<%= f.collection_select:p1,:id,Player.all,:id,:name %> 15:<! - <%= f.select:p1,Player.all.collect {| e | [e.name,e.id]}%> - > 16:17:
Kiran 2013-03-27 20:11:16

+0

對不起,我原來的回答是錯誤的。我更新了它。再試一次? – 2013-03-27 20:13:16

+0

嗯,回到原點。這是產生p1 [team_id],我想要的是團隊[p1] ..基本上上述是導致錯誤的行爲。我必須切換到我的原始形式'<%= f.collection_select:p1,Player.all,:id,:name%>',因爲團隊自動從f來。然而,這使我回到我發佈的原始問題:( – Kiran 2013-03-27 21:36:28

相關問題