【问题标题】:Sorting nested form fields in rails对rails中的嵌套表单字段进行排序
【发布时间】:2012-02-29 22:07:03
【问题描述】:

我正在尝试创建一个根据产品类别对产品进行分类的库存表单。理想情况下,我将能够按类别列出这些产品,并将放入一些 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 的模型,它有_many 个产品。如何在控制器和表单中按类别分类和分隔我的产品?另外,有没有办法使用 Formtastic 做到这一点?谢谢!

【问题讨论】:

    标签: ruby-on-rails forms nested-attributes


    【解决方案1】:

    实际上实现起来非常简单。在带有属性position 的nest_form 字段中添加一个隐藏字段(当然将此属性添加到您的模型中)并将其添加到您的js 以及使用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);
          });
        }
      });  
    

    这是我在_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"
    

    这真的很好用。

    【讨论】:

    • 谢谢!我认为您的解决方案是按类别对项目进行排序,我希望只显示该类别的项目。我最终弄明白了,但你的回答一路帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-27
    • 2013-02-06
    • 2021-03-06
    • 2020-04-13
    相关资源
    最近更新 更多