Rails:更新嵌套属性 - nil的未定义方法`to_sym':NilClass

时间:2011-09-10 21:10:58

标签: ruby-on-rails nested-attributes

修改:添加了更新操作,以及错误发生在哪一行

型号:

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])

2 个答案:

答案 0 :(得分:8)

我已经弄清楚了。我读到像MatchTeams这样的连接表不需要ID。我猜这不是做任何嵌套表单时都是如此。我重新删除我的迁移删除了id列的排除,现在一切正常。难道我们都不喜欢这个愚蠢的错误吗? :)

答案 1 :(得分:0)

如果没有在代码中看到有问题的to_sym,只要知道它附加的东西没有被正确定义。如果这是@var.to_sym之类的变量,您最有可能:

  1. 尚未设置@var
  2. 设置它,但它返回nil,因为没有匹配项(例如@var = @project.companies.first@project没有公司绑定它。)
  3. 您遗失了params中的相关数据位。如果你的to_sym依赖于通过表单提交的数据,那么如果用户遗漏了你假设的数据,它将无法工作。在这种情况下,您应首先测试数据是否在运行.to_sym之前输入。