Why does my form_for :blog point to /blogs/new?
我正在针对SO帖子查看实例变量vs符号在ruby上的Rails形式。
根据投票最多的答案
if you use symbol :post it creates
1 | <form action="/posts" method="post"> |
if you use the instance @post
for @post = Post.new you will get
1 | <form action="/posts/create" class="new_account" id="new_account" method="post"> |
但是当我查看渲染的html页面时
1 2 3 4 | <form action="/blogs/new" accept-charset="UTF-8" method="post"> <input name="utf8" type="hidden" value="" /> <input type="hidden" name="authenticity_token" ...... |
用于
new.html.erb
1 2 3 4 5 | <%=form_for :blog do |f|%> <%= f.text_field :title%> <%= f.text_field :content%> <%= f.submit :button %> <% end %> |
这使我出错,提示
1 2 | Routing Error No route matches [POST]"/blogs/new" |
为什么路径不匹配?
对于资源,您的表格对于
_form.html.erb
1 2 3 4 5 | <%=form_for @blog do |f|%> <%= f.text_field :title%> <%= f.text_field :content%> <%= f.submit :button %> <% end %> |
您的控制器操作应创建此实例变量:
BlogsController
1 2 3 4 5 6 7 | def new @blog = Blog.new end def update @blog = Blog.find(params[:id]) end |
最后,您的模板应该只调用部分
new.html.erb
1 | render partial: :form |
update.html.erb
1 | render partial: :form |
您链接的答案相对较旧,我很确定不再正确。
Rails的实现方法是使用实??例变量。
然后应使用
1 | <form action="/blogs" method="post"> |
动作url将是
形式的url呈现
http://apidock.com/rails/ActionView/Helpers/FormHelper/form_for
When the model is
represented by a string or symbol, as in the example above, if the
:url option is not specified, by default the form will be sent back to
the current url