Is it the Rails way to use form helper markup?

2019-07-31 03:43发布

问题:

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?

回答1:

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.