2011-09-10 8 views
4

編集:追加、およびエラーが発生した行ものに更新アクションRailsは:更新ネストされた属性 - 未定義のメソッド `to_sym」をnilにするために:NilClass

モデル:

class Match < ActiveRecord::Base 
    has_and_belongs_to_many :teams 
    has_many :match_teams 
    has_many :teams, :through => :match_teams 
    accepts_nested_attributes_for :match_teams, :allow_destroy => true 
end 

コントローラ:

def new 
    @match = Match.new 
    @match_teams = 2.times do 
     @match.match_teams.build 
    end 

    respond_to do |format| 
     format.html # new.html.erb 
     format.json { render json: @match } 
    end 
    end 

    def update 
    @match = Match.find(params[:id]) 

    respond_to do |format| 
     if @match.update_attributes(params[:match]) 
     format.html { redirect_to @match, notice: 'Match was successfully updated.' } 
     format.json { head :ok } 
     else 
     format.html { render action: "edit" } 
     format.json { render json: @match.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

ネストされたモデル:

class MatchTeam < ActiveRecord::Base 
    belongs_to :match 
    belongs_to :team 
end 

協会:

class Team < ActiveRecord::Base 
    has_and_belongs_to_many :matches 
end 

ビュー:

<%= form_for(@match) do |f| %> 

    <%= f.fields_for :match_teams, @match_teams do |builder| %> 
    <%= builder.collection_select :team_id, Team.all, :id, :name, :include_blank => true %> 
    <% end %> 

    <% unless @match.new_record? %> 
    <div class="field"> 
     <%= f.label :winning_team_id %><br /> 
     <%= f.collection_select :winning_team_id, @match.teams, :id, :representation %> 
    </div> 
    <% end %> 

    <div class="actions"> 
    <%= f.submit %> 
    </div> 
<% end %> 

のparams:

Processing by MatchesController#update as HTML 
Parameters: {"utf8"=>"Ô£ô", "authenticity_token"=>"QIJChzkYOPZ1hxbzTZS8H3AXc7i 
BzkKv3Z5daRmlOsQ=", "match"=>{"match_teams_attributes"=>{"0"=>{"team_id"=>"1", " 
id"=>""}, "1"=>{"team_id"=>"3", "id"=>""}}, "winning_team_id"=>"3"}, "commit"=>" 
Update Match", "id"=>"2"} 

2つのチームが正常に動作して新しいマッチを作成するには、編集ビューでも正しい値を示しているが、更新処理によってこのエラーが発生します。

undefined method `to_sym' for nil:NilClass 
app/controllers/matches_controller.rb:65:in `block in update' 

line 65: if @match.update_attributes(params[:match]) 
+1

更新アクションのコードを表示するとよいでしょう。 –

+0

''未定義メソッド 'to_sym' for nil:NilClass'はどこから来たのですか? (ファイル+ライン番号) –

+0

残念な人、不足している情報で投稿を編集しました。 – Frexuz

答えて

8

私はそれを理解しました。 MatchTeamsのような結合テーブルにIDが必要ないことを読んだ。私はこれがネストされたフォームを実行していないときに当てはまると思います。 id列の除外を削除してマイグレーションを再開したところ、すべて正常に動作しました。私たちは皆、この愚かな誤りを愛していないのですか? :)

0

あなたのコードで問題to_symを見なければ、ちょうどそれが接続だ事が適切に定義されていないことを知っています。これはのような@var.to_sym、あなた最も可能性の高い変数の場合:

  1. すべて
  2. 設定し、それに@varを設定していないが、しかし、一致がないので、それがnilを返します(例:@var = @project.companies.firstしかし@projectはに結び付けられない企業を持っていませんそれ)。
  3. paramsに関連するデータがありません。 to_symがフォームから送信されたデータに依存している場合、ユーザーが想定しているデータのビットを省略しても機能しません。この場合、まずデータを入力してから.to_symを実行する前にテストする必要があります。
関連する問題