Ruby on rails 为什么:符号的表单返回到同一页?
我有一个表单,它被我的新模板和编辑模板用于名为product的模型。在我的控制器中,对于创建和更新操作,它重定向到@product,然后在成功时呈现“show”。当使用'form_for@product do | f |声明表单时,这可以正常工作,但是如果使用符号而不是实例变量,它会尝试发布到同一页面。也就是说,如果我在products/4/edit页面上,并在表单上按下submit,它会给我一个路由错误,即它试图发布products/4/edit,而在参考资料中只有一个GET路由 现在,如果我输入url选项“url:products\u path”,它会正确地重定向到products/4,就像我在@product中使用form\u一样。这是否意味着使用带有形式_的符号不会影响我的控制器操作?为什么要尝试向自己发帖 这是表格Ruby on rails 为什么:符号的表单返回到同一页?,ruby-on-rails,Ruby On Rails,我有一个表单,它被我的新模板和编辑模板用于名为product的模型。在我的控制器中,对于创建和更新操作,它重定向到@product,然后在成功时呈现“show”。当使用'form_for@product do | f |声明表单时,这可以正常工作,但是如果使用符号而不是实例变量,它会尝试发布到同一页面。也就是说,如果我在products/4/edit页面上,并在表单上按下submit,它会给我一个路由错误,即它试图发布products/4/edit,而在参考资料中只有一个GET路由 现在,如果我
<%= form_for @product do |f| %> <-- Changing this to :product gives routing error
<% if @product.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@product.errors.count, "error") %> prohibited this product from being saved:</h2>
<ul>
<% @product.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :description %><br>
<%= f.text_area :description, rows: 6 %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
当您在表单中使用符号时,它基本上会告诉表单生成器您创建表单的对象类型。如果碰巧有一个实例变量集,例如@product,那么表单甚至可以在呈现输入变量时拾取值。然而,为了通过rails资源路由确定正确的url路径,您需要传递一个资源 @产品与:产品不同。实例变量反映系统中的资源,因此可以为其生成资源路由。使用符号时并非如此,这就是为什么需要显式设置url参数的原因
使用:产品时,表单操作的url设置为当前页面的url,这就是为什么您的提交将转到编辑操作。啊,我想是这样的!谢谢你的澄清
def create
@product = Product.new(product_params)
respond_to do |format|
if @product.save
format.html { redirect_to @product, notice: 'Product was successfully created.' }
format.json { render :show, status: :created, location: @product }
else
format.html { render :new }
format.json { render json: @product.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if @product.update(product_params)
format.html { redirect_to @product, notice: 'Product was successfully updated.' }
format.json { render :show, status: :ok, location: @product }
else
format.html { render :edit }
format.json { render json: @product.errors, status: :unprocessable_entity }
end
end
end