创建编辑表单的最佳方法是什么?

What Is The Best Method To Create Edit Forms?

我正在 Rails Ruby 中处理一个应用程序 (Ruby 2 - Rails 4 - Bootstrap 3)

我已经使用 simple_form gem 来构建表单,例如注册和注册,但是如何创建一个从数据库加载对象并允许用户编辑的表单细节?

假设我们在数据库中有一个产品 table,我想创建一个表单来将该产品的详细信息加载到表单中,并允许用户编辑产品的描述、价格等。

我看了一圈,还是不太清楚

谢谢。

首先,您需要将视图中的 link 放入编辑操作中,您将产品作为参数发送到索引中 (app/views/products/index.html.erb) .它应该看起来像这样:

<%= link_to 'Edit', edit_product_path(product) %>

然后你需要确保你的产品控制器中有编辑操作 (app/controllers/products_controller.rb):

 def edit
 end

现在您的编辑。html.erb (app/views/products/edit.html.erb) 应该如下所示:

<h1>Editing product</h1>

<%= render 'form' %>

<%= link_to 'Show', @product %> |
<%= link_to 'Back', product_path %>

最后,您呈现的表单应位于 app/views/_form。html.erb 应如下所示:

<%= 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 :name %><br>
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :price %><br>
    <%= f.text_field :price %>
  </div>
  <div class="field">
    <%= f.label :description %><br>
    <%= f.text_field :descriptions %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

提示:当您使用 rails generate Scaffold 命令生成 Scaffold 时,它会自动为您的模型和所有视图创建编辑、删除、显示和新操作以及我提到的 类以上。

rails generate Scaffold Product name:string description:text price:decimal

希望对您有所帮助!