Rails是否使用表单助手标记? [英] Is it the Rails way to use form helper markup?

查看:100
本文介绍了Rails是否使用表单助手标记?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读表单助手指南 http://guides.rubyonrails.org/form_helpers.html ,但我不确定是否真的需要以这种方式编写我的网页。



我有一个写在 new.html.erb

 < form action =/ postsmethod =post > 
< label for =title>测试< / label>
< input id =title/>
< input type =submitvalue =submit/>
< / form>

文章页面来自< a href =http://guides.rubyonrails.org/getting_started.html =nofollow>开始指南)



提交时请求,服务器抛出 ActionController :: InvalidAuthenticityToken 异常。

所以我将它改为

 <%= form_for:post,url:{action:create} do | f | %GT; 
< label for =title>测试< / label>
< input id =title/>
< input type =submitvalue =submit/>
<%end%>

现在我拥有相同的表单,除了服务器现在接受请求。



表单帮助程序是在Rails视图中开发表单的正确方式吗?

解决方案

是的。

Rails方式将您重写为:

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

您使用直接HTML标记的尝试被Rails在其所有非GET请求。您必须使用Rails表单标记或移除CSRF保护以避免该错误。


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?

解决方案

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.

这篇关于Rails是否使用表单助手标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆