【问题标题】:Country expected, got String error预期国家/地区,出现字符串错误
【发布时间】:2011-04-19 12:34:23
【问题描述】:

我有 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 作为字符串字段。在联盟控制器中,我有这个来填充下拉列表:@countries = Country.dropdown_list。在联盟/新视图中,我有这个选择字段:<%= f.select :country, @countries %>。出了什么问题?

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 我刚刚这样做了:&lt;%= f.select :artist, Artist.all.collect {|a| [a.name, a.id] } %&gt; 并得到了这个Artist(#2198585660) expected, got String(#2151988680)
      • @JoeSak ,我遇到了同样的问题,我在控制器的允许参数列表中添加了 :artist 而不是 :artist_id
      【解决方案3】:

      我收到了这个错误:

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

      【讨论】:

      • 你把这个放在哪里了,艺术家模特?
      • @hubble 你把验证放在哪里了?
      • 无论是“belongs_to”还是“has_one”艺术家
      【解决方案4】:

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

      【讨论】:

        【解决方案5】:

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

        当您的表单中有两个字段时会导致此错误:

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

        然后 rails 将崩溃并出现错误:expected Hash (got String) for param

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

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

        【讨论】:

          【解决方案6】:

          我收到了这个错误:

          期望国家 (#xxx),得到字符串 (#xxx) 这就是我在 Rails 3.0.x 中修复它的方式:

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-05-08
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-07-11
            相关资源
            最近更新 更多