Ruby on rails Rails嵌套表单错误:未定义方法“update#u attributes';零级:零级
我使用的是Mongoid,很棒的gem和rails 3.2.8 我的功能在客户端上工作(添加多个字段),但是当我尝试保存时,我得到一个“未定义的方法`update\u attributes` for nil:NilClass”错误 以下是所有相关信息: profile.rbRuby on rails Rails嵌套表单错误:未定义方法“update#u attributes';零级:零级,ruby-on-rails,ruby-on-rails-3,mongoid,nested-forms,Ruby On Rails,Ruby On Rails 3,Mongoid,Nested Forms,我使用的是Mongoid,很棒的gem和rails 3.2.8 我的功能在客户端上工作(添加多个字段),但是当我尝试保存时,我得到一个“未定义的方法`update\u attributes` for nil:NilClass”错误 以下是所有相关信息: profile.rb class Profile include Mongoid::Document include Mongoid::Timestamps has_many :skills, :autosave =&g
class Profile
include Mongoid::Document
include Mongoid::Timestamps
has_many :skills, :autosave => true
accepts_nested_attributes_for :skills, allow_destroy: true
attr_accessible :skills_attributes
end
class Skill
include Mongoid::Document
belongs_to :profile
field :skill_tag, :type => String
end
# PUT /profiles/1
# PUT /profiles/1.json
def update
@profile = Profile.find(params[:id])
respond_to do |format|
if @profile.update_attributes(params[:profile])
format.html { redirect_to @profile, notice: 'Profile was successfully updated.' } # Notice
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @profile.errors, status: :unprocessable_entity }
end
end
end
技能.rb
class Profile
include Mongoid::Document
include Mongoid::Timestamps
has_many :skills, :autosave => true
accepts_nested_attributes_for :skills, allow_destroy: true
attr_accessible :skills_attributes
end
class Skill
include Mongoid::Document
belongs_to :profile
field :skill_tag, :type => String
end
# PUT /profiles/1
# PUT /profiles/1.json
def update
@profile = Profile.find(params[:id])
respond_to do |format|
if @profile.update_attributes(params[:profile])
format.html { redirect_to @profile, notice: 'Profile was successfully updated.' } # Notice
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @profile.errors, status: :unprocessable_entity }
end
end
end
查看
<%= simple_form_for(@profile) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<div class="items">
<%= f.nested_fields_for :skills do |f| %>
<fieldset class="item">
<%= f.input :skill_tag, :label => 'Skills:' %>
<a href="#" class="remove">Remove Skill</a>
<%= f.hidden_field :id %>
<%= f.hidden_field :_destroy %>
</fieldset>
<% end %>
</div>
<a href="#" class="add">Add Skill</a>
</div>
<div class="form-actions">
<%= f.button :submit, :class => 'btn' %>
</div>
<% end %>
************更新***************
我最终切换到Ryan的嵌套表单gem,它就像一个符咒一样工作。您的消息直接指向失败的执行行,因此:
if @profile.update_attributes(params[:profile])
问题是@profile
实例变量是nil
,rails无法找到nil
对象的update\u attributes
方法
通过进入启动应用程序的终端,您可以轻松地检查服务器日志中的params
散列,查看params[:id]
(可能根本没有定义)
或者,您可以在应用程序文件夹中查看开发日志:
tail -n 1000 development.log | egrep params
我认为更新方法中的@profile为零。请使用profiles/id检查http put请求。是的,问题确实发生在更新方法中。但我不确定您要检查什么。您是否正确获取参数[:id]?