【问题标题】:Railscast 198, but using formtasticRailscast 198,但使用 formtastic
【发布时间】:2011-06-30 21:18:27
【问题描述】:

在使用 Formtastic 单独编辑多条记录时,您如何做到RyanB's Railscast 中介绍的内容? Formtastic 不使用 RyanB 的方法所依赖的 form_tag。

【问题讨论】:

  • 您仍然可以在 formtastic 表单中使用普通表单助手。
  • 不是 form_tag,根据 Justin French 的说法:link“Formtastic 不能与 form_tag 一起使用。”

标签: ruby-on-rails ruby-on-rails-3 forms formtastic


【解决方案1】:

semantic_form_for 只是form_for 的包装,因此您可以使用相同的参数。这是Ryan Bates' screencast的formtastic版本@

views/products/edit_individual.html.erb

<% semantic_form_for :update_individual_products, :url => update_individual_products_path, :method => :put do |f| %>
  <% for product in @products %>
    <% f.fields_for "products[]", product do |ff| %>
      <h2><%=h product.name %></h2>
      <%= render "fields", :f => ff %>
    <% end %>
  <% end %>
  <p><%= submit_tag "Submit" %></p>
<% end %>

views/products/index.html.erb

<% semantic_form_for :edit_individual_products, :url => edit_individual_products_path do %>
  <table>
    <tr>
      <th></th>
      <th>Name</th>
      <th>Category</th>
      <th>Price</th>
    </tr>
  <% for product in @products %>
    <tr>
      <td><%= check_box_tag "product_ids[]", product.id %></td>
      <td><%=h product.name %></td>
      <td><%=h product.category.name %></td>
      <td><%= number_to_currency product.price %></td>
      <td><%= link_to "Edit", edit_product_path(product) %></td>
      <td><%= link_to "Destroy", product, :confirm => 'Are you sure?', :method => :delete %></td>
    </tr>
  <% end %>
  </table>
  <p>
    <%= select_tag :field, options_for_select([["All Fields", ""], ["Name", "name"], ["Price", "price"], ["Category", "category_id"], ["Discontinued", "discontinued"]]) %>
    <%= submit_tag "Edit Checked" %>
  </p>
<% end %>

请注意,您也可以在 formtastic 中使用 form_for 助手。

更新

如果您也喜欢使用嵌套属性,它应该开箱即用,在表单部分使用 fields_for。让我们继续使用 railscast 的例子,然后说:

产品.rb

has_many :commments
accepts_nested_attributes_for :comments

您可以在产品的 _fields.html.erb 上编辑 cmets,例如:

<%= f.fields_for :comments do |cf| %>
  <%=render 'comments/fields', :f=>cf%>
<%end%>

并确保您的 cmets 视图中有一个部分字段。

【讨论】:

  • 太棒了,谢谢!我将此应用于 Ryan 的其他关于编辑多个的教程,并将 edit_multiple 视图更新为 rails 3 我必须手动声明非静止控制器操作和方法的路径,如下所示:= semantic_form_for :isbn, :url =&gt; {:controller =&gt; 'isbns', :action =&gt; 'update_multiple'}, :html=&gt;{:method=&gt;:put} do |f| 现在如果我能得到它与 accept_nested_attributes_for 合作,我在笑……
  • 更新了我的答案,向您展示如何将它与嵌套属性一起使用。
  • 你好!除了,哼,我不能让它工作。我可以说服你看看我关于这个新问题link 的代码。非常感谢您的帮助。
  • 嗨@dombesz,你能看看stackoverflow.com/questions/26456913/…。我想我对问答模型有类似的问题,我想你可能对我有一些指示。已经谢谢了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-29
  • 2012-11-13
  • 2010-12-29
  • 1970-01-01
  • 2015-05-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多