2012-02-29 77 views
4

我正在尝试创建一个基于其类别对产品进行排序的清单表单。理想情况下,我可以将这些产品按类别列出,并会放入一些JavaScript来隐藏/显示给定类别的产品。在轨中排序嵌套表单域

目前,我在包装方面遇到了困难,无法将我的产品按类别划分为我的形式。这是我目前有(Ryan Bates的Railscasts嵌套属性模仿):

class InventoriesController < ApplicationController 
def new 
    @title = "Take Inventory" 
    @vendor = ProductVendor.find(params[:product_vendor_id]) 
    @inventory = Inventory.new() 
    @products = @vendor.products.active 
    @products.each do |product| 
    @inventory_line_item = @inventory.inventory_line_items.build({:product_id => product.id}) 
    end 
end 

我对新的库存形式:

<%= form_for @inventory do |f| %> 
<table> 
    <tr> 
    <th>Item</th> 
    <th>Quantity</th> 
    </tr> 

<% f.fields_for :inventory_line_items do |builder| %> 

<tr> 
    <td><%= builder.object.product.name %></td> 
    <td><%= builder.text_field(:quantity, :size => 3) %></td> 
     <%= builder.hidden_field :product_id %> 
</tr> 

<% end %> 

</table> 
<%= f.hidden_field(:user_id, :value => current_user.id) %> 
<%= f.hidden_field(:location_id, :value => current_location.id) %> 
<%= f.hidden_field(:product_vendor_id, :value => @vendor.id) %> 

<%= f.submit "Submit" %> 

<% end %> 

所以我叫PRODUCT_CATEGORY说的has_many产品另一种模式。如何根据控制器和表单对产品进行分类和分类?另外,有没有办法使用Formtastic来做到这一点?谢谢!

回答

6

这实际上很容易实现。与属性position(添加此ATTR到你的课程模式)的nest_form字段中添加隐藏字段,这与使用jQuery的ui.js

$('#task_fields').sortable({ 
    items: '.fields', 
    dropOnEmpty: true, 
    cursor: 'move', 
    handle: '.move', 
    opacity: 0.4, 
    scroll: true, 
    axis:'y', 
    placeholder: 'ui-state-highlight', 
    start: function(e, ui) { 
     ui.placeholder.height(ui.item.height()); 
    }, 
    update: function() { 
     $(this).children(".fields").each(function(index) { 
     $(this).children('input.task_position').val(index + 1); 
     }); 
    } 
    }); 

这里一起添加到您的JS就是我在我的_form.html.haml

= f.fields_for :tasks do |t| 
    = t.text_field :name 
    = t.hidden_field :position, :class => :task_position 
    = t.collection_select :account_id, Account.all, :id, :full_name, :prompt => 'Assign task to...' 
    .button-group 
    %span{:class => "button icon no-text move pill"} 
    = t.link_to_remove "", :class => "button icon no-text remove pill" 
= f.link_to_add "Add a Task", :tasks, :class => "button icon add" 

这个工作非常出色。

+0

谢谢!我认为您的解决方案是按类别对项目进行排序,我只希望显示该类别的项目。我最终找出了答案,但你的答案一路走来。 – NicSlim 2012-03-27 18:52:27

+0

太好了。很高兴我能帮上忙! – Marc 2012-03-27 18:57:43