Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Updating Nested attributes - undefined method `to_sym' for nil:NilClass

Edit: Added the update action, and on what line the error occurs

Model:

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

Controller:

  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

Nested model:

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

Association:

class Team < ActiveRecord::Base
  has_and_belongs_to_many :matches
end

View:

<%= 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"}

Creating a new match with 2 teams work fine, the edit view also shows the correct values, but the update action gives me this error.

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])
like image 925
Frexuz Avatar asked Sep 10 '11 21:09

Frexuz


1 Answers

I've figured it out. I read that a join table like MatchTeams doesn't need an ID. I'm guessing this is true when not doing any nested forms. I redid my migration removing the exclusion of the id column, and now everything works fine. Don't we all love this stupid errors? :)

like image 113
Frexuz Avatar answered Oct 22 '22 18:10

Frexuz