Jshoe523
Jshoe523

Reputation: 4191

Before_action not getting called on ajax requests

I have a very simple delete method below:

before_action :get_post, only: [:delete_post]

def delete_post
  post.destroy
  head :no_content
end

private
def get_post
  post = Post.find(params[:id])
end

For some reason, my ajax call to delete the post doesn't call the before_action so the post variable is essentially never defined. Everything works fine if I just move the declaration into the delete_post method and get rid of the before_action.

Any idea why this is? Am I missing something? Thanks

EDIT: This doesn't work with any of my methods that are called through ajax requests. I just used this delete method for simplicity

Upvotes: 1

Views: 291

Answers (1)

dimuch
dimuch

Reputation: 12818

You are using local post variables, try to use instance variable @post instead.

before_action :get_post, only: [:delete_post]

def delete_post
  @post.destroy
  head :no_content
end

private
def get_post
  @post = Post.find(params[:id])
end

Upvotes: 2

Related Questions