【问题标题】:Active Record Association Type MismatchActive Record 关联类型不匹配
【发布时间】:2014-09-18 18:37:06
【问题描述】:

我在这样的匹配中嵌套了结果

/matches/16/results/13/edit

我有以下选择字段,这显示了正确的信息(team.name 及其 team.id)

<%= f.collection_select :winner, @select_winner_loser, :id, :name %>

现在,当我尝试编辑结果并选择获胜者时,我得到了:

ActiveRecord::AssociationTypeMismatch 需要团队(#10504340),得到字符串(#6163240)

“当分配给关联的对象类型不正确时引发。” http://api.rubyonrails.org/classes/ActiveRecord/AssociationTypeMismatch.html

Winner是一个team对象,result.rb看起来像这样

class Result < ActiveRecord::Base
    has_one :match
    belongs_to  :winner, class_name: "Team"
    belongs_to  :loser, class_name: "Team"
end

@select_winner_loser 来自我的 results_controller

  def edit
    @select_winner_loser = []
    @select_winner_loser << @match.top
    @select_winner_loser << @match.bottom
  end

Match.top & bottom 也是团队对象

class Match < ActiveRecord::Base
    belongs_to  :top, class_name: "Team"
    belongs_to  :bottom, class_name: "Team"
    ...
    belongs_to  :result
end

我不明白为什么我会得到这个,因为我的选择字段中有正确的对象,有什么想法吗?

谢谢

【问题讨论】:

    标签: ruby-on-rails activerecord ruby-on-rails-4


    【解决方案1】:

    改变

    <%= f.collection_select :winner, @select_winner_loser, :id, :name %>
    

    <%= f.collection_select :winner_id, @select_winner_loser, :id, :name %>
    

    以及相应的允许参数。当 Rails 看到名称中的 _id 时,它会创建一个 Team 对象。

    【讨论】:

    • 谢谢你 lunr :),不得不更改我的迁移文件,我的数据库中有 win 而不是 Winner_id,并进行了你指出的更改。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-25
    • 2017-10-14
    • 2014-12-06
    • 2022-01-26
    相关资源
    最近更新 更多