关于ruby on rails:为什么我的form_for:blog指向/ blogs / new?

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"

为什么路径不匹配?


对于资源,您的表格对于show.html.erbnew.html.erb应该都是通用的。在这种情况下,应将表单分成部分_form.html.erb,并用实例变量替换:blog

_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的实现方法是使用实??例变量。

然后应使用<%= form_for @Blog.new do |f| =>。这应该呈现为

1
<form action="/blogs" method="post">


动作url将是

形式的url呈现

基于该对象的路径(在路径中定义)的form_for"blog的动作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