开发者

How do I fix an unexpected nil object error?

开发者 https://www.devze.com 2023-02-28 18:01 出处:网络
I have this error when I try to add a comment via AJAX: ActionView::Template::Error (You have a nil object when you didn\'t expect it!

I have this error when I try to add a comment via 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'

The form to create the comment has an association option that should set the comment_title for the 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" %>开发者_Python百科
<% end %>

Here's the create action in my comments controller:

def create
  @comment = @video.comments.new(params[:comment].merge({:user_id => current_user.id}))
  if @comment.save
    respond_to do |format|
      format.html { redirect_to :back }
      format.js
    end
  else
    respond_to do |format|
      format.html { redirect_to :back, :alert => "Unable to add comment." }
      format.js { render 'fail_create.js.erb' }
    end
  end
end

Why am I getting this error? How can I resolve this?


You can't use this:

dom_id(@comment.comment_title)

You can use this

dom_id(@comment)

Because you should pass a record, but not a string

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

UPD

as far as comment_title is a has_one association (but not an attribute, as I thought), so the problem is it isn't created so it passes nil into dom_id method

0

精彩评论

暂无评论...
验证码 换一张
取 消