gpt4 book ai didi

ruby-on-rails - rails : Updating Nested attributes - undefined method `to_sym' for nil:NilClass

转载 作者:行者123 更新时间:2023-12-03 13:55:53 26 4
gpt4 key购买 nike

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

模型:

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

嵌套模型:
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 %>

参数:
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 个团队创建新比赛工作正常,编辑 View 也显示正确的值,但更新操作给了我这个错误。
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])

最佳答案

我已经想通了。我读到像 MatchTeams 这样的连接表不需要 ID。我猜当不做任何嵌套表单时这是真的。我重新进行了迁移,删除了 id 列的排除,现在一切正常。我们不是都喜欢这种愚蠢的错误吗? :)

关于ruby-on-rails - rails : Updating Nested attributes - undefined method `to_sym' for nil:NilClass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7374734/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com