代码之家  ›  专栏  ›  技术社区  ›  kchucke

数组中名称列表中的多个对象

  •  0
  • kchucke  · 技术社区  · 7 年前

    enter image description here 我试图为数组中的每个名称创建一个单独的记录。数组通过一个控制器中的一个表单生成,单个记录需要保存在连接(类型)表中(我知道mongo中没有“连接”表,但这是描述它的最佳方式)。目前使用Mongoid/MongoDB运行Rails 5。

    原始形式:

        <%= form_tag create_multiple_batch_keg_index_path, method: 
            :create do |form|%>
            <div class="field">
            <table class="table table-hover table-condensed">
            <thead>
            <tr>
              <th>Select All</th>
              <th>Keg Name</th>
            </tr>
            </thead>
            <tbody>
              <% Keg.each do |batch_keg| %>
                  <tr>
                    <td><%= check_box_tag 'batch_keg_ids[]', batch_keg.id 
                    -%> </td>
                    <td><%= batch_keg.name -%> </td>
                  </tr>
              <% end %>
            </tbody>
            </table>
            </div>
    

    原始控制器参数:

        def batch_params
         params.require(:batch).permit(:batch_keg_attributes => [keg_id, 
         :active, :visible, :wholesale_inventory, :taproom_inventory, 
         :hold_inventory])
        end 
    

        def create_multiple
         batch_keg_ids(params).flatted.map{|ids| 
         BatchKeg.create(:wholesale_inventory => true, :taproom_inventory 
         => true, :hold_inventory => false, :active => true, :visible => 
         true)}redirect_to batches_url
        end
    

    路线

        resources :batch_keg do
         collection do
          post :create_multiple
          put :update_multiple
          get :collection
         end
        end
    

    我认为我已经成功地完成了大部分过程(到目前为止,我已经处理了几个错误消息,但我被卡住了)。我搜索了所有的互联网,试图找到一个解决方案,但没有找到一个有效的。我要么A),接近但不太接近,要么B)完全偏离轨道。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Ryan K    7 年前

    错误信息很清楚。你正在通过 params 作为参数输入 batch_kegs_ids ,但该方法不需要任何参数。此外,它看起来像

    我也会改变 create_multiple 方法

     def create_multiple
       params[:batch_keg_ids].each do |id| 
         BatchKeg.create(keg_id: id, wholesale_inventory: true, taproom_inventory: true, hold_inventory: false, active: true, visible: true)
       end
       redirect_to batches_url
     end