Is it the Rails way to use form helper markup?

核能气质少年 提交于 2020-01-15 17:36:23

问题


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.



来源:https://stackoverflow.com/questions/19300064/is-it-the-rails-way-to-use-form-helper-markup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!