D
D
dexdev2013-12-11 07:05:00
Ruby on Rails
dexdev, 2013-12-11 07:05:00

ActiveRecord::RecordInvalid in CommentsController#create. How to transfer a user?

I'm trying to assign a user but rails complains ActiveRecord::RecordInvalid in CommentsController#create Errors occurred: User cannot be empty

# Not implemented: check to see whether the user has permission to create a comment on this object
        @comment = Comment.build_from(@obj, current_user, @comment_hash[:body])
        if @comment.save!
          render :partial => "comments/comment", :locals => { :comment => @comment }, :layout => false, :status => :created
        else
          redirect_to root_path

written in the controller
class CommentsController < ApplicationController
 def create
        @comment_hash = params[:comment]
        @obj = @comment_hash[:commentable_type].constantize.find(@comment_hash[:commentable_id])
        # Not implemented: check to see whether the user has permission to create a comment on this object
        @comment = Comment.build_from(@obj, current_user, @comment_hash[:body])
        if @comment.save!
          render :partial => "comments/comment", :locals => { :comment => @comment }, :layout => false, :status => :created
        else
          redirect_to root_path
        end
      end
end

I can't understand what is the problem?
Using rails 4.0.0.0
ruby ​​2.0.0
gem 'acts_as_commentable_with_threading', :github => 'elight/acts_as_commentable_with_threading', :branch => 'master'
based on article twocentstudios.com/blog/2012/11/15/simple-ajax- com...
Help please

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Kolosov, 2013-12-11
@satisFUCKtor

@comment = Comment.build_from(@obj, current_user, @comment_hash[:body])

apparently current_user is empty :)

B
Boris Penkovsky, 2013-12-22
@Able1991

there are two options, either curent_user returns an object of class not an Active Record, or generally nil if you send an Ajax request and do not write

beforeSend: function(xhr) {
                xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
           }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question