我看到这个answer和this都声称将符号传递给form_for之间的区别,即
<% form_for :post do |f| %>
和
<% form_for @post do |f| %>
一个区别是action = /posts/create
,但我发现了一些不同的内容,实际上action=/posts
而不是声明的内容。
当你传递一个实例时,你得到了
<form class="new_form" id="new_form" action="/forms"
但是当你传递一个符号时,你会得到
<form action="/forms"
(对于两个html版本我省略了字符集和隐藏等)
那是怎么回事?
答案 0 :(得分:1)
<% form_for :post do |f| %>
和<% form_for @post do |f| %>
之间的区别在于后者binds the form to a model instance。
后者实际上将“保留”用户在提交后键入的值。 form_for :post
只是使用多态路由获取路径并将输入嵌套在键:post
下。
两者都生成动作/posts
(对于新记录),除非你真的弄乱了路线。如果记录为form_for @post
,/posts/:id
将生成到#persisted?
的路由,并将方法更改为修补程序。
这些是由资源创建的conventional routes:
GET /posts posts#index
GET /posts/:id posts#show
GET /posts/new posts#new
POST /posts posts#create
GET /posts/:id/edit posts#edit
PATCH|PUT /posts/:id posts#update
DELETE /posts/:id posts#destroy
/posts/create
不是常规路线,除非您手动定义路线,否则永远不会生成。