Rails 4. How to add authenticity_token to forms received through partial?

In my rails application, there are two meta tags on all pages in the chapter section:

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

In those forms that are not displayed using partial, there is a hidden field authenticity_token

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

But this field skips if I just upload the form as follows:

 <%= render 'shared/comment_form' %> 

Is this the expected behavior? Do I have to manually add authenticity_token , and if so, how do I check it?

Edit:

generic /_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 %> 

In addition, adding <input type="hidden" name="authenticity_token" id="authenticity_token" value="ANYTHING" /> to this form still allows you to post information and create a new record ...

+6
source share
2 answers

In your case, we have two ways:

  • Add authenticity_token: true to form option

  • Manually add an authenticity_token field to the field, for example:

<%= hidden_field_tag :authenticity_token, form_authenticity_token -%>

+25
source

So, this looks like remote forms, not forms loaded via partial:

The default value for config.action_view.embed_authenticity_token_in_remote_forms has been changed to false. This change breaks up remote forms that should also work without JavaScript, so if you need this behavior, you can either set it to true or explicitly pass authenticity_token: true in the form parameters.

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

+2
source

All Articles