2012-04-05 9 views
5

埋め込みフォームを更新しようとするとActiveSupport::HashWithIndifferentAccessエラーが発生します。埋め込みフォームの更新時に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]オブジェクトでありますubmission:

:players_to_team

ActiveSupport::HashWithIndifferentAccessエラーは何を意味するのでしょうか?このフォームでplayers_to_teamのエントリを更新するにはどうすればよいですか?

編集

BTplayers_to_teamsの列です。 field_forブロックを削除すると、BTフィールド/ players_to_teams行を正常に保存できます。

+0

ないということである - そのフィールドの正しい名前がオンになっていますplayers_to_teamsのテーブル? –

+0

はい。詳細を提供するために質問が更新されました。 –

+0

"<%= field.fields_for @ players_to_teams.player"を "<%= field.fields_for:player"に変更することができます –

答えて

5

クレジットが@Brandanに行く

感謝。回答:What is the difference between using ":" and "@" in fields_for

いいえ、サンプルプロジェクトをクローンしてエラーを再現できました。 私は何が起こっているのか理解していると思います。

accepts_nested_attributes_forを呼び出した後、player_attributes =という名前のモデルに インスタンスメソッドが追加されました。これは、通常、has_one の関連付けに対して定義されているplayer =メソッドに加えて、 にあります。 player_attributes =メソッドは 属性のハッシュを受け取りますが、player =メソッドは実際のPlayer オブジェクトのみを受け入れます。ここで

あなたはplayers_to_teams.player @ fields_for を呼び出したときに生成されたテキスト入力の例です:プレーヤー:

、ここだfields_for呼び出す 同じ入力その

すると、あなたのコントローラであなた コールupdate_attributes最初の例では player =を呼び出し、2番目の例ではplayer_attributes =を呼び出します。 の場合、メソッドに渡される引数はハッシュです( paramsは最終的にハッシュのハッシュなので)。

これは、AssociationTypeMismatchを取得した理由です。 ハッシュをplayer =に渡すことはできず、Playerオブジェクトのみに渡すことはできません。

accepts_nested_attributes_forでfields_forを使用する唯一の安全な方法は、アソシエーション自体ではなく アソシエーションの名前を渡すことです。

だからあなたの元の質問に答えるために、違いは1つが 動作し、他の属性「BT」されているもの:-)

関連する問題