国家预期,得到字符串错误

Joh*_*ohn 6 ruby-on-rails

我有2个模型"国家"和"联盟",国家有很多联赛和联盟属于国家.添加联盟时,我有一个包含国家/地区的列表框,在提交表单时,会发送实际国家/地区:

{"commit"=>"Create League",
 "authenticity_token"=>"wuAuj5vowkk2R56TuFkWE8J3x3vue5RbnNPcbpjuG3Q=",
 "utf8"=>"✓",
 "league"=>{"league_short"=>"CL",
 "country"=>"England",
 "level"=>"2",
 "league"=>"The Championship"}}
Run Code Online (Sandbox Code Playgroud)

但后来我收到此错误消息:

Country expected, got String
Run Code Online (Sandbox Code Playgroud)

在Country模型中,我将country_id(整数)和country(字符串)作为字段,在League模型中,我将country作为字符串字段.在联盟控制器中,我有这个打赌下拉:@countries = Country.dropdown_list.在联盟/新视图中,我有这个选择字段:<%= f.select :country, @countries %>.出了什么问题?

Jon*_*Roy 8

您需要使用:country_id而不是:country

<%= f.select :country_id, Country.all.collect {|c| [c.name, c.id]} %>
Run Code Online (Sandbox Code Playgroud)


Joe*_*Sak 7

我收到了这个错误:

Artist (#xxx) expected, got String (#xxx)
Run Code Online (Sandbox Code Playgroud)

这就是我在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 %>
Run Code Online (Sandbox Code Playgroud)

因此,当我将collection_select输入的方法设置为外键而不是模型名称时,它就起作用了


Sye*_*lam 5

您需要在该请求中发送country_id(这是主键)而不是名称"England".关系与主键相关联.

<%= f.select :country, Country.all.collect {|c| [ c.name, c.id ] } %>
Run Code Online (Sandbox Code Playgroud)

  • 我刚做了这个:`<%= f.select:artist,Artist.all.collect {| a | [a.name,a.id]}%>`并得到了这个艺术家(#2198585660)的预期,得到了字符串(#2151988680) (21认同)