2011-04-19 63 views
4

我有2個模型「國家」和「聯賽」,國家有很多聯賽和聯賽屬於國家。當添加一個聯賽,我有國家列表框和表單提交時,實際的國發:國家預期,得到字符串錯誤

{"commit"=>"Create League", 
"authenticity_token"=>"wuAuj5vowkk2R56TuFkWE8J3x3vue5RbnNPcbpjuG3Q=", 
"utf8"=>"âœ「", 
"league"=>{"league_short"=>"CL", 
"country"=>"England", 
"level"=>"2", 
"league"=>"The Championship"}} 

但後來我收到此錯誤信息:

Country expected, got String 

在全國模型我有country_id(整數)和國家(字符串)作爲字段,在聯盟模型中我有國家作爲字符串字段。在聯盟控制器中,我有這樣的下拉菜單:@countries = Country.dropdown_list。在聯盟/新視圖中,我有這個選擇字段:<%= f.select :country, @countries %>。出了什麼問題?

回答

4

您需要在該請求中發送country_id(這是主鍵)而不是名稱'England'。這些關係與主鍵相關聯。

<%= f.select :country, Country.all.collect {|c| [ c.name, c.id ] } %> 
+0

謝謝,工作! – John 2011-04-20 05:42:13

+18

我只是這樣做了:'<%= f.select:artist,Artist.all.collect {| a | [a.name,a.id]}%>'並且得到了這個'藝術家(#2198585660)預計,得到了String(#2151988680)' – 2011-05-10 15:50:10

7

我得到這個錯誤:

Artist (#xxx) expected, got String (#xxx) 

這是我如何在Rails的3.0.x的固定它:

class OtherModel 
    belongs_to :artist 

    validates :artist, :presence => true 

    #... 
end 

<%= form_for_other.collection_select :artist_id, 
            Artist.all, :id, :name, 
            :prompt => true %> 

所以工作時,我設置的方法對collection_select輸入到外鍵而不是型號名稱

+1

你把這個,藝術家模型放在哪裏? – Will 2013-06-15 23:32:27

+0

@ hubble你在哪裏放置驗證? – 2013-11-05 22:45:40

+0

在任何模型「belongs_to」或「has_one」藝術家 – 2013-12-04 01:08:48

1

聯盟模型應該引用國家的id(country_id)a nd不是字符串。

7

您需要使用:COUNTRY_ID代替:國家

<%= f.select :country_id, Country.all.collect {|c| [c.name, c.id]} %> 
0

別人誰遇到了同樣的問題:

,當你在你的表格一樣有兩個字段導致此錯誤:

video: 'some string' 
video['url']: 'some url' 

然後導軌會崩潰,並出現以下錯誤:預計散列(得到字符串)爲參數

解決方案非常簡單:將「視頻」更改爲其他內容。例如:

video_origin_url: 'some string' 
video['url']: 'some url' 
0

我得到這個錯誤:

國家(#XXX)預期,得到了字符串(#XXX) 這就是我如何在Rails的3.0.x的固定它:

<%= f.collection_select :country_id, Country.all.collect, :id, :name %> 
相關問題