1

I am reading the guide on form helpers http://guides.rubyonrails.org/form_helpers.html but I'm not sure whether I actually need to write my webpages this way..

I have an HTML form like this written in new.html.erb

<form action="/posts" method="post">
  <label for="title">Test</label>
  <input id="title"/>
  <input type="submit" value="submit"/>
</form>

(The posts page is from the Getting Started guide)

When I submit the request, the server throws an ActionController::InvalidAuthenticityToken exception.

So I changed it to

<%= form_for :post, url: {action: "create"} do |f| %>
  <label for="title">Test</label>
  <input id="title"/>
  <input type="submit" value="submit"/>
<% end %>

And now I have the same form, except the server now accepts the request.

Are form helpers the proper way to develop forms in Rails views?

2
  • 2
    Yes, thats what they're there for. Use them for the form tag, the inputs, the error rendering, everything. api.rubyonrails.org/classes/ActionView/Helpers/… Commented Oct 10, 2013 at 15:32
  • Everyone has already mentioned how you should use it and that it has to do with CSRF. The thing is, you won't have the same form. Using form_for, if you inspect the HTML, you'll see a div underneath the declaration of the form with hidden inputs, one of which is for the authenticity_token, which you need. Commented Oct 10, 2013 at 15:52

1 Answer 1

2

Generally, yes.

"Rails way" would have you rewrite this as:

<%= form_for Post.new do |f| %>
  <%= f.label :title, "Test" %>
  <%= f.input :title %>
  <%= f.submit %>
<% end %>

Your attempt to use the straight HTML tag was prevented by the CSRF protection that Rails uses on all of its non-GET requests. You must use the Rails form tags or remove CSRF protection to avoid that error.

Sign up to request clarification or add additional context in comments.

1 Comment

and removing the CSRF protection is not recommended.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.