【问题标题】:How to render same form on the same page?如何在同一页面上呈现相同的表单?
【发布时间】:2012-07-01 03:07:37
【问题描述】:

我很想知道这是怎么做到的。假设我有一个简单的Product 模型,并且在一个页面上想要单击一个链接并通过 AJAX 添加一个产品表单。我比弹出其他产品表单,完成第一个并提交它并对其他产品做同样的事情。

这是我将使用的代码。


在索引页面上,您可以通过链接添加产品表单,创建它并在列表中查看它。

products/index.html.erb

<h1>Products</h1>

<%= link_to "Product", new_product_path, :remote => true %>

<div id="product_form">
  <%= render 'form' %>
</div>

<ul id="products">
  <%= render :partial => @products.reverse %>
</ul>

products/_form.html.erb

<%= form_for(@product, :remote => true) do |f| %>
    <%= f.text_field :name %>
    <%= f.text_field :price %>
  <%= f.submit %>
<% end %>

products/_product.html.erb

<%= content_tag_for(:li, product) do %>
  <p><%= product.name</p>
  <p><%= product.price %></p>
<% end %>

ProductsController

def index
  @products = Product.all
  @product = Product.new
end

def create
  @product = Product.new(params[:product])

  respond_to do |format|
    if @product.save
      format.html { redirect_to products_url }
      format.js
    else
      format.html { render action: "index" }
      format.js
    end
  end
end

当它被创建时,它应该在 _product 部分显示产品。

products/create.js.erb

$('#products').prepend('<%= escape_javascript(render(@product)) %>');

点击链接后,产品表单会出现在&lt;div id="product_form"&gt;

products/new.js.erb

$("#product-form").html("<%= escape_javascript(render(:partial => 'products/form', locals: { product: @product })) %>");

现在这会生成一个产品表单,但我想知道在同一页面上呈现其他产品表单背后的代码逻辑。这将如何实现?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1


    【解决方案1】:

    通常我使用代表产品集合的第二个对象来执行此操作。如果它符合您的业务逻辑(例如 ProductCategory 或 ShoppingCart)或简单的 ActiveModel“产品”,则它可以是一个活动记录,它具有保存每个相关产品的保存方法。

    Active Presenter 可以为您提供有关此机制的更多详细信息,但我不会使用该 gem,因为它的活动性很低。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-20
      • 1970-01-01
      • 2021-05-28
      • 1970-01-01
      • 1970-01-01
      • 2020-03-02
      • 2020-04-22
      相关资源
      最近更新 更多