Railscast 198, but using formtastic

2019-02-14 19:53发布

问题:

How could you do what's covered in RyanB's Railscast on editing multiple records individually, using Formtastic? Formtastic doesn't use form_tag, which RyanB's method relies on.

回答1:

The semantic_form_for is just a wrapper around form_for so you can use the same parameters. Here is a formtastic version of Ryan Bates' screencast

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 %>

Please note that you can use the form_for helpers as well in formtastic.

Update

If you like to use nested attributes as well it should work out of the box, using fields_for on the form partial. Lets stick with the railscast example and say that:

product.rb

has_many :commments
accepts_nested_attributes_for :comments

You can edit the comments on the _fields.html.erb of the products like:

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

And make sure you have a fields partial in your comments views.