【问题标题】:ActiveSupport::HashWithIndifferentAccess on Embedded Form Update嵌入式表单更新上的 ActiveSupport::HashWithIndifferentAccess
【发布时间】:2012-04-05 01:58:21
【问题描述】:

我在尝试更新嵌入式表单时收到 ActiveSupport::HashWithIndifferentAccess 错误。

这是最简单的例子:

表格:

<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] 对象:

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

编辑

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

谢谢

【问题讨论】:

  • 什么是属性“BT”——这是表格 player_to_teams 上字段的正确名称吗?
  • 是的。已更新问题以提供更多信息。
  • 你能把“
  • 这就是我最终做的事情并且它有效。你知道这是为什么吗?我在这里发布了它:stackoverflow.com/questions/10021980/…
  • 因为你创建了一个几乎相同的问题,你应该删除这个

标签: ruby-on-rails forms activesupport


【解决方案1】:

归功于@Brandan。回复:What is the difference between using ":" and "@" in fields_for

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

在您调用 accept_nested_attributes_for 之后,您现在有一个 模型上名为 player_attributes= 的实例方法。这是在 除了通常为 has_one 定义的 player= 方法之外 协会。 player_attributes= 方法接受一个哈希 属性,而 player= 方法只接受一个实际的 Player 对象。

这是您调用时生成的文本输入示例 fields_for @players_to_teams.player:

&lt;input name="players_to_team[player][name]" ... /&gt; 就是这样 调用fields_for :player时输入相同:

&lt;input name="players_to_team[player_attributes][name]" ... /&gt;当你 在您的控制器中调用update_attributes,第一个示例将调用 player=,而第二个示例将调用 player_attributes=。在 在这两种情况下,传递给方法的参数都是哈希(因为 params 最终只是散列的散列)。

这就是你得到AssociationTypeMismatch的原因:你不能通过 player= 的哈希值,只有一个 Player 对象。

看来,将fields_foraccepts_nested_attributes_for 是通过传递名称 关联,而不是关联本身。

所以要回答你原来的问题,不同的是一个有效 而另一个没有:-)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-03
    • 2015-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-17
    相关资源
    最近更新 更多