2012-04-05 66 views
5

当我尝试更新嵌入式表单时,出现ActiveSupport::HashWithIndifferentAccess错误。ActiveSupport :: HashWithIndifferentAccess on Embedded Form Update

下面是最简单的例子:

形式:

<h1>PlayersToTeams#edit</h1> 
<%= form_for @players_to_teams do |field| %> 
    <%= field.fields_for @players_to_teams.player do |f| %> 
     <%= f.label :IsActive %> 
     <%= f.text_field :IsActive %> 
    <% end %> 
    <%= field.label :BT %> 
    <%= field.text_field :BT %> 
    <br/> 
    <%= field.submit "Save", class: 'btn btn-primary' %> 
<% end %> 

型号:

class PlayersToTeam < ActiveRecord::Base 
    belongs_to :player 
    belongs_to :team 

    accepts_nested_attributes_for :player 
end 

class Player < ActiveRecord::Base 
    has_many :players_to_teams 
    has_many :teams, through: :players_to_teams 
end 

控制器:

class PlayersToTeamsController < ApplicationController 
    def edit 
    @players_to_teams=PlayersToTeam.find(params[:id]) 
    end 

    def update 
    @players_to_teams=PlayersToTeam.find(params[:id]) 
    respond_to do |format| 
     if @players_to_teams.update_attributes(params[:players_to_team]) 
     format.html { redirect_to @players_to_teams, notice: 'Player_to_Team was successfully updated.' } 
     format.json { head :no_content } 
     else 
     format.html { render action: "edit" } 
     format.json { render json: @players_to_teams.errors, status: :unprocessable_entity } 
     end 
    end 
    end 
end 

这是在表单的所述params[:players_to_team]对象ubmission:

:players_to_team

是什么的ActiveSupport::HashWithIndifferentAccess错误是什么意思?我需要做什么才能让此表单更新players_to_team条目?

编辑

BT是在players_to_teams一列。如果我删除field_for块,我可以成功保存BT字段/ players_to_teams行。

谢谢

+0

是什么属性“BT” - 是一个字段的正确名称上表players_to_teams? – 2012-04-05 02:09:14

+0

是的。问题更新提供更多信息。 – 2012-04-05 02:12:23

+0

你能否将“<%= field.fields_for @ players_to_teams.player”更改为“<%= field.fields_for:player” – 2012-04-05 03:05:39

回答

5

信用评论@Brandan。已回答:What is the difference between using ":" and "@" in fields_for

好的,我能克隆你的示例项目,并重现错误。 我想我明白发生了什么。

在您致电accep_nested_attributes_for后,您现在在名为player_attributes =的模型上有一个 实例方法。除了通常为has_one 关联定义的player =方法外,还有 。 player_attributes =方法接受 属性的散列,而player =方法只接受实际玩家 对象。

这里的时候,你叫 fields_for @ players_to_teams.player生成的文本输入的例子:

和这里的那 相同的输入调用fields_for时:玩家:

当你的控制器,你 通话update_attributes方法,第一个示例将调用 player =,而第二个示例将调用player_attributes =。在 这两种情况下,传递给该方法的参数都是散列(因为 params最终只是散列的散列)。

这就是为什么你得到一个AssociationTypeMismatch:你不能通过 哈希到player =,只有一个Player对象。

看起来,使用fields_for与 accep_nested_attributes_for的唯一安全方式是传递 关联的名称,而不是关联本身。

所以回答你原来的问题,不同的是,一个工作 和其他没有:-)

相关问题