user4965201
user4965201

Reputation: 973

Rails update Multiple Records at once getting error unknown attribute

Ihave a rails app in which i want to update the same field of the multiple records at once. this is my form in the view

<tbody>
     <%= form_tag update_cart_cart_path, method: "PUT"  do |f| %>
          <% @cart_items.each do |cart_item| %>
            <tr class="items">
             <td><a class="remove" href="#"><fa class="fa fa-close"></fa></a></td>
             <td><%= image_tag cart_item.variant.variant_photos[0].variant_image %></td>
              <td><a class="aa-cart-title" href="#"><%= cart_item.variant.name %></a></td>
              <td>Rs. <%= cart_item.variant.price %>/kg</td>
              <td><%= fields_for "cart_items[#{cart_item.id}]" do |p| %>

             <%= p.text_field 'quantity' %>
                          <% end %></td>
             <td><input class="aa-cart-quantity product-quantity" rel="<%= cart_item.variant.price %>" type="number" value="<%= cart_item.quantity %>"></td>
             <td>Rs. <%= (cart_item.variant.price) * (cart_item.quantity) %></td>
               </tr>
                <% end %>

               <td colspan="6" class="aa-cart-view-bottom">
                  <input type="submit" value="submit">
                <%#= link_to 'Update Cart', '#', :class => 'hvr-shutter-in-horizontal button' %>

               </td>
                  </tr>
        <% end %>
  </tbody>

and my controller is

def update_cart
  @cart_items = CartItem.where(cart_id: params[:id])
  @cart_items.each do |item|
    item.update_attributes(update_cart_params)
  end
end

private

def update_cart_params
  params.require(:cart_items).permit!
end

Now the issue i am facing is when i try to update the cart_item records i get the error message unknown attribute '2' for CartItem.

these are the params i am getting after submit

Parameters: {"utf8"=>"✓", "authenticity_token"=>"5dlZZhW5UCw+dZfalPnqQmNKzkNHVLcwvt8luitOE7NojtkFDmdwwTzKi+DrFioOrpG8gcekRuQRZYYj0OKJHg==", "cart_items"=>{"2"=>{"quantity"=>"121"}, "3"=>{"quantity"=>"111"}}, "id"=>"1"}

Please Help

Upvotes: 0

Views: 111

Answers (1)

Fred
Fred

Reputation: 1627

The problem is that you are trying to update each of your cart items with the parameters for all the cart items.

You should try the following:

  • Grab the cart
  • For each cart item params :
    • Find the cart item belonging to the cart
    • Update the cart items with the corresponding attributes

Pseudo code, not tested, but you'll get the idea :

def update_cart
    @cart = Cart.find(params[:id])
      update_cart_params.keys.each do |cart_item_id|
       cart_item = @cart.items.find(cart_item_id)
         if cart_item
           cart_item.update(update_cart_params[cart_item_id])
         end
     end
 end

Upvotes: 3

Related Questions