当使用符号或实例var时,rails form_for是否使用相同的路由?

时间:2014-10-24 00:40:48

标签: ruby-on-rails

这只是关于助手&#34; form_for&#34;的一般性问题。我正在使用<%= 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

我以为我已经读过&#34; form_for:product&#34;将搜索同名的实例变量并使用相同的路径product_path,但似乎我错了。我看过这个网站上的其他帖子,但他们似乎并没有提到这些路线。为什么我收到此错误?

编辑:我添加了选项&#34; url:products_path&#34;到form_for:产品系列,现在可以使用了。我猜这个符号并不知道在@product这样的资源中使用路由吗?

1 个答案:

答案 0 :(得分:0)

如果您有路由错误,请检查文件confg / routes.rb它必须包含资源:产品。如果没有,请添加它并重新启动服务器。

在路线上我们使用带有表名称(模型的复数)的符号来定义资源。

编辑:

使用form_for使用实例变量:在控制器上初始化的@product,其中包含空的新产品或要更新的finded产品。