总结一下form_for的一些用法
2018-10-06 本文已影响1人
Hollow_Knight
form_for 的基本用法
<%= form_for @article do |f|%>
<p><%= f.label :title %></p>
<p><%= f.text_field :title %></p>
<p><%= f.label :content %></p>
<p><%= f.text_area :content %></p>
<p><%= f.submit %></p>
<% end %>
生成的html代码
<form class="new_article" id="new_article" action="/articles" accept-charset="UTF-8" method="post">
<input name="utf8" type="hidden" value="✓" />
<input type="hidden" name="authenticity_token" value="T/93nWpeIkRVxuYqbjKWgruBx/nWLtRRTMVPzCEf3gDfJhDbdGhXXGaENfnC7wC6E3tXTnF/QWRyG3kxV9DlJw==" />
<p><label for="article_title">Title</label></p>
<p><input type="text" name="article[title]" id="article_title" /></p>
<p><label for="article_content">Content</label></p>
<p><textarea name="article[content]" id="article_content">
</textarea></p>
<p><input type="submit" name="commit" value="Create Article" data-disable-with="Create Article" /></p>
</form>
这里的@article
是一个model对象
<p><%= f.label :title %></p>
<p><%= f.text_field :title %></p>
生成的表单是
<p><label for="article_title">Title</label></p>
<p><input type="text" name="article[title]" id="article_title" /></p>
后面的字段就是数据库中的字段互相对应,参数可以在params[:article][:title]拿到
可以看到还有两个隐藏的input标签,这段代码不会在浏览器中显示,只在 Rails 内部有用,所以你并不需要知道它的作用。简单来说,这段代码首先使用 Unicode 字符 ✓(对号 ✓)强制浏览器使用正确的字符编码提交数据,然后是一个“真伪令牌”(authenticity token),Rails 用它抵御“跨站请求伪造”(Cross-Site Request Forgery,简称 CSRF)攻击。
<%= form_for(@article, as: :client) do |f| %>
...
<% end %>
此时params
中取值不会在params[:article]
中取而是在params[:client]
中取相当于给了一个别名。
<%= form_for @post, as: :post, url: posts_path, html: { class: "new_post", id: "new_post" } do |f| %>
...
<% end %>
在html参数中可以定义很多自定义的属性"data":"xxxx"
非常方便。
<%= form_for @post, remote: true do|f| %> #使用剥离式js异步提交
= form_for( @post, html: { class: "form" }) do |f|
......
= f.select :tag_list, @tags.collect { |t| [t.name,t.name] }, {}, { :multiple => "multiple" }
......