加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 在rails中对嵌套表单字段进行排序

发布时间:2020-12-17 03:02:17 所属栏目:百科 来源:网络整理
导读:我正在尝试创建一个库存表单,根据其类别对产品进行排序.理想情况下,我将能够按类别列出这些产品,并将添加一些 javascript来隐藏/显示给定类别的产品. 目前,我无法解决如何在我的表单中按类别拆分产品的问题.这是我目前所拥有的(模仿Ryan Bates的嵌套属性的Ra
我正在尝试创建一个库存表单,根据其类别对产品进行排序.理想情况下,我将能够按类别列出这些产品,并将添加一些 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的模型,它有很多产品.如何在控制器和表单中按类别对产品进行排序和分类?另外,有没有办法使用Formtastic做到这一点?谢谢!

解决方法

它实际上非常简单.在nest_form字段中添加一个带有属性位置的隐藏字段(当然将此attr添加到您的模型中)并将其添加到您的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"

这非常有效.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读