【发布时间】:2014-10-24 00:40:48
【问题描述】:
这只是一个关于助手“form_for”的一般问题。我正在使用教科书编写一个程序,该程序有一个使用<%= form_for(@product) do |f| %> 的表单文件。该表单由新模板和编辑模板共享。但是,我看到很多教程使用符号 (:product) 而不是实例变量。所以,我试着交换它们看看会发生什么。碰巧它在尝试提交表单时给了我一个路由错误:
No route matches [POST] "/products/new"
和
No route matches [POST] "/products/5/edit"
代码如下:
<%= form_for(:product) do |f| %>
<% 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 :price %><br>
<%= f.text_field :price %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
在product_controller中
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
# PATCH/PUT /products/1
# PATCH/PUT /products/1.json
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
我以为我读过“form_for :product”会搜索同名的实例变量并使用相同的路径 product_path,但我似乎弄错了。我看过这个网站上的其他帖子,但他们似乎没有提到路线。为什么会出现此错误?
编辑:我在 form_for :product 行中添加了选项“url: products_path”,它现在可以工作了。我猜这个符号不知道像@product 那样使用资源中的路由?
【问题讨论】:
-
嗯,这似乎不能解释路由问题。只有标签改变
-
如果您遇到路由错误,请检查文件
confg/routes.rb,它必须包含resources :products。如果没有,添加它并重新启动服务器。 -
它就在那里。使用符号算作资源吗?我知道使用 @ 确实并且会知道路径。
-
如果符号像
@一样被实例化为一个对象,那么是的,它将具有相同的路由行为。 form_for 中的对象将调用 POST(或可能是补丁),除非您定义了您希望 form_for 方法如何发布。
标签: ruby-on-rails