Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActionController::InvalidAuthenticityToken Error in controller

So I've started getting this error after I tried to implement AJAX comments in my rails app:

ActionController::InvalidAuthenticityToken in CommentsController#create    

ActionController::InvalidAuthenticityToken

    def handle_unverified_request
      raise ActionController::InvalidAuthenticityToken
    end
  end
end

Here are all the codes from the relevant files:

comments_controller.rb

class CommentsController < ApplicationController


  before_action :find_post

  def create  
    @comment = @post.comments.build(comment_params)
    @comment.user_id = current_user.id

    if @comment.save
      respond_to do |format|
        format.html { redirect_to root_path }
        format.js
      end
    else
      flash[:alert] = "Check the comment form, something went horribly wrong."
      render root_path
    end
  end

Add comments form:

= form_for([post, post.comments.build], remote: true) do |f|
  = f.text_field :content, placeholder: 'Add a comment...', class: "comment_content", id: "comment_content_#{post.id}"

views/comments/create.js.erb

$('#comments_<%= @post.id %>').append("<%=j render 'comments/comment', post: @post, comment: @comment %>");
$('#comment_content_<%= @post.id %>').val('')

comment.rb

class Comment < ActiveRecord::Base
  belongs_to :user
  belongs_to :post
end

I have no idea what's causing this error as it worked fine before the introduction of AJAX. I looked up answers to similar problems on stackoverflow and added protect_from_forgery at the top of comments_controller.rb to no avail. I don't get the InvalidAuthenticityToken error alright, but instead, it gives me a different error:

NoMethodError in CommentsController#create

undefined method `id' for nil:NilClass

def create  
  @comment = @post.comments.build(comment_params)
  @comment.user_id = current_user.id #highlighted line

  if @comment.save
    respond_to do |format|
like image 948
Arif Avatar asked Sep 20 '26 08:09

Arif


1 Answers

Solution to my problem was to put on first line inside controller:

skip_before_action :verify_authenticity_token, :only => [:create,:inquire_enterprise]

As you can see I am escaping 2 actions which produced the error.

like image 176
Nezir Avatar answered Sep 22 '26 00:09

Nezir