2011-09-10 23 views
4

編輯:新增更新操作,並在哪一行發生錯誤的Rails:更新嵌套屬性 - 未定義的方法`to_sym」的零: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

nil:NilClass'的'undefined method'to_sym'來自哪裏? (文件+行號) –

+0

對不起,傢伙,編輯與丟失信息的職位。 – Frexuz

回答

8

我已經想通了。我讀到像MatchTeams這樣的連接表不需要ID。我猜這是沒有做任何嵌套表單時的情況。我redid我的遷移刪除排除id列,現在一切工作正常。難道我們都不喜歡這個愚蠢的錯誤嗎? :)

0

沒有看到違規to_sym在你的代碼,只知道它連接到的東西還沒有被正確定義。如果這是一個變量,如@var.to_sym,你最有可能:

  1. 在所有
  2. 設置它沒有建立@var,但它的返回nil,因爲沒有匹配(如@var = @project.companies.first@project有沒有企業綁它)。
  3. 您錯過了params中的相關位數據。如果您的to_sym依賴於通過表單提交的數據,那麼如果用戶遺漏了您所假設的那部分數據,它將不起作用。在這種情況下,您應該先測試一下,看看數據是否在運行.to_sym之前輸入。
相關問題