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

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

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

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

 Country expected, got String 

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

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

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

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

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

我收到了这个错误:

 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输入的方法设置为外键而不是模型名称时,它就起作用了

联盟模型应该通过其id(country_id)而不是字符串来引用国家/地区。

对于遇到同样问题的其他人:

如果表单中有两个字段,则会导致此错误:

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

然后rails将崩溃并出现错误:预期的参数哈希(获得字符串)

解决方案非常简单:将“video”更改为其他内容。 例如:

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

我收到了这个错误:

国家(#xxx)预期,得到String(#xxx)这就是我在Rails 3.0.x中修复它的方法:

 <%= f.collection_select :country_id, Country.all.collect, :id, :name %>