Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4. How to add authenticity_token to forms rendered via partial?

On my rails app, on all pages, in the head section there are these 2 meta tags:

<meta name="csrf-param" content="authenticity_token" />
<meta name="csrf-token" content="027GUZBeEkmv..." />

On forms not rendered using a partial there is a hidden authenticity_token field

<input type="hidden" name="authenticity_token" value="D5TddQruJppDD3..." />

But this field misses if I simply load the form like this:

<%= render 'shared/comment_form' %>

Is this expected behavior ? Should I manually add an authenticity_token and if so how do I validate it ?

Edit:

shared/_comment_form.html.erb

<%= form_for([@post, @comment], :html => { :onsubmit => "validateCommentForm(event)" }, remote:true) do |f| %>
    <%= render 'shared/error_messages', object: f.object %>
    <div class="field">
        <%= f.text_area :content, placeholder: "Add to the article. Make it be more" %>
    </div>

    <%= f.submit "Save", class: "btn btn-info" %>
<% end %>

Also, adding <input type="hidden" name="authenticity_token" id="authenticity_token" value="ANYTHING" /> to that form still manages to post the info and create a new record...

like image 991
Catalin Avatar asked Mar 15 '16 00:03

Catalin


2 Answers

In your case, we have two ways to do:

  1. Add authenticity_token: true in form options

  2. Manually add authenticity_token field into form, like this:

<%= hidden_field_tag :authenticity_token, form_authenticity_token -%>

like image 79
Thieu Nguyen Avatar answered Sep 23 '22 12:09

Thieu Nguyen


Ok, so it seems it's about remote forms and not forms loaded via a partial:

Changed default value for config.action_view.embed_authenticity_token_in_remote_forms to false. This change breaks remote forms that need to work also without JavaScript, so if you need such behavior, you can either set it to true or explicitly pass authenticity_token: true in form options.

Found answer here: https://github.com/rails/rails/issues/10608

like image 45
Catalin Avatar answered Sep 22 '22 12:09

Catalin