如何修复意外的nil对象错误?

时间:2011-04-22 20:30:02

标签: ruby-on-rails ruby ruby-on-rails-3 debugging

当我尝试通过AJAX添加评论时出现此错误:

ActionView::Template::Error (You have a nil object when you didn't expect it!
You might have expected an instance of ActiveRecord::Base.
The error occurred while evaluating nil.to_key):
1: $("#<%= dom_id(@comment.comment_title) %>").parent().append('<%= escape_javascript(render(@comment)) %>');
2: $(".comment_form")[0].reset();
  app/views/comments/create.js.erb:1:in `_app_views_comments_create_js_erb___503385093_2173588800_0'
  app/controllers/comments_controller.rb:8:in `create'

创建评论的表单有一个关联选项,可以设置comment_title的{​​{1}}:

comment

以下是我的评论控制器中的创建操作:

<%= simple_form_for([@video, @video.comments.new], :remote => true) do |f| %>
  <%= f.association :comment_title, :collection => @video.comment_titles.map {|ct| [ct.title, comment_title_path(ct)] }, :label => "Comment Title:", :include_blank => false %>
  <%= f.input :body, :label => false, :placeholder => "Post a comment." %>
  <%= f.button :submit, :value => "Post" %>
<% end %>

为什么我收到此错误?我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

你不能用这个:

dom_id(@comment.comment_title)

您可以使用此

dom_id(@comment)

因为您应该传递记录,而不是字符串

http://apidock.com/rails/ActionController/RecordIdentifier/dom_id

<强> UPD

至于comment_titlehas_one关联(但不是我认为的属性),所以问题是它没有被创建,所以它将nil传递给{{ 1}}方法