2012-02-29 4 views
4

カテゴリに基づいて製品を並べ替える在庫フォームを作成しようとしています。理想的には、これらの製品をカテゴリー別にリストさせることができ、特定のカテゴリーの製品を隠す/表示するためのJavaScriptをいくつか入れます。レールでネストされたフォームフィールドを並べ替える

現在のところ、私の製品をカテゴリー別に分割する方法については、私の頭の中でラップするのに問題があります。ここで私は現在、(ネストされた属性のライアン・ベイツ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 %> 

は、だから私はそれにhas_many製品PRODUCT_CATEGORYと呼ばれる別のモデルを持っています。コントローラとフォームのカテゴリ別に製品を並べ替えて分けるにはどうすればよいですか?また、Formtasticを使ってこれを行う方法はありますか?ありがとう!

答えて

6

実際に実装するのはかなり簡単です。 (もちろん、あなたのモデルにこのATTRを追加)属性positionとnest_formフィールドに隠しフィールドを追加し、

$('#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); 
     }); 
    } 
    }); 

をjqueryの-ui.jsを使用して一緒にあなたの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

+0

お役に立てて嬉しいです! – Marc