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|
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With