Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails link_to destroy method fails due to invalid authenticity token

I have the following haml code which generates a button:

= link_to 'Delete',
        MODEL_path(MODEL),
        class: 'data-type-button btn btn-negative',
        data: { confirm: 'delete it now!!! ... ?' },
        method: :delete

After pressing the delete button generated, and confirming via the popup that I do want to proceed with the deletion, I am brought to an error screen. This screen tells me that I have an invalid authenticity token. The same code where link_to is replaced with button_to, however, works as it should and the item is deleted.

I want this to be a link_to and not a button_to because of the way that the resulting HTML code lines up. How can I get the link_to to work?

like image 520
Thomas Deranek Avatar asked Sep 13 '25 07:09

Thomas Deranek


2 Answers

Confirm you have the csrf meta tag in your layout and in the HTML HEAD section.

= csrf_meta_tag
like image 130
Mark Swardstrom Avatar answered Sep 15 '25 21:09

Mark Swardstrom


As it turns out, link_to passes parameters via the contents inside of the parenthesis following the path. So in order to get the authenticity token to be passed as a parameter while also using a link_to, you can use the following modification of that code

= link_to 'Delete',
        MODEL_path(id: MODEL.id, authenticity_token: form_authenticity_token),
        class: 'data-type-button btn btn-negative',
        data: { confirm: 'Delete it now!!! ... ?' },
        method: :delete

I actually knew the answer when I posted the question, but after spending a lot of time trying to figure this out and not finding the solution directly on google anywhere, I wanted to post my solution to help any other lost souls out there. I don't know if that is bad practice on this website or not, but if it helps someone then I'm okay with it.

like image 22
Thomas Deranek Avatar answered Sep 15 '25 21:09

Thomas Deranek