# How to add several items in shopping cart in rails?

**URL:** <https://www.ruby-forum.com/t/how-to-add-several-items-in-shopping-cart-in-rails/259668>\
**Category:** Uncategorized\
**Created:** [May 28, 2020, 10:59am UTC](https://www.ruby-forum.com/t/how-to-add-several-items-in-shopping-cart-in-rails/259668 "2020-05-28T10:59:37Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![Wishka](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/bb73d2/32.png) [@Wishka](https://www.ruby-forum.com/u/Wishka)\
**Post date:** [May 28, 2020, 10:59am UTC](https://www.ruby-forum.com/t/how-to-add-several-items-in-shopping-cart-in-rails/259668/1 "2020-05-28T10:59:37Z")

</div>

I have some problem in my simple shop in rails. I want to add group of chosen products in cart, but I don’t know how.

I use radio buttons on my 3 groups of products and I want user choose all 3 items and then press the button “add to cart”.

In cart it’s must by array like this: username-mix(1-id, 2-id, 3-id). But i have one more problem. I can’t get id’s of my products and don’t know why. And this is main.

Products are all from `seed.db` with fields: `:category_id, :menu_id, :title, :price, :discribe and :path_to_image` .

Here is my code:

```auto
class ProductController < ApplicationController
   before_action :admin_user, only: :edit

   def show
     @products = Product.where("category_id = 1").limit(3)
     @products2 = Product.where("category_id = 2").limit(3)
     @products3 = Product.where("category_id = 3").limit(3)
   end

   private

   def product_params
     params.permit(
       :category_id,
       :menu_id,
       :title,
       :discribe,
       :price,
       :path_to_image
     )
   end
 end

```

My `Product` model:

```auto
class Product < ApplicationRecord
  validates :title, presence: true
  validates :price, presence: true
  belongs_to :category
end

```

`product/show/html.erb`

```auto
<div class="col-md-4 about-left">
  <table class="tfood">
    <td><p><b>Main</b></p></td>
    <% @products.each do |i| %>
      <tr>
        <td>
          <%= i.title %><%= image_tag i.path_to_image %>
        </td>
        <td>
          <%= i.discribe %>
          <p><b>Price: <%= i.price %></b></p>
          <input name="main" type="radio" value="">
        </td>
      </tr>
    <% end %>
  </table>
</div>
<div class="col-md-4 about-left">
  <table class="tfood">
    <td>
      <p><b>Topping</b></p>
    </td>
    <% @products2.each do |i| %>
      <tr>
        <td>
          <%= i.title %>
          <%= image_tag i.path_to_image %>
        </td>
        <td>
          <%= i.discribe %>
          <p><b>Price: <%= i.price %></b></p>
          <input name="topping" type="radio" value="">
        </td>
      </tr>
    <% end %>
  </table>
</div>
<div class="col-md-4 about-left">
  <table class="tfood">
    <td>
      <p><b>Drink</b></p>
    </td>
    <% @products3.each do |i| %>
      <tr>
        <td>
          <%= i.title %>
          <%= image_tag i.path_to_image %>
        </td>
        <td>
          <%= i.discribe %>
          <p><b>Price: <%= i.price %></b></p>
          <input name="drink" type="radio" value="">
        </td>
      </tr>
    <% end %>
  </table>
</div>
<script>
  function add_to_cart(id){
    var x = window.localStorage.getItem(id);
    x = x * 1 + 1;
    window.localStorage.setItem(id, x);
  }
</script>

```

---

<div class="post-metadata">

**Author:** ![SouravGoswami](https://www.ruby-forum.com/user_avatar/www.ruby-forum.com/souravgoswami/32/2543_2.png) [@SouravGoswami](https://www.ruby-forum.com/u/SouravGoswami)\
**Post date:** [May 29, 2020, 12:08pm UTC](https://www.ruby-forum.com/t/how-to-add-several-items-in-shopping-cart-in-rails/259668/2 "2020-05-29T12:08:48Z")

</div>

I am just starting with Rails. So my opinion can be bad practice, but what about migrating the User database to add a field `cart` of type string? That way when the user adds one item to the card, it’s inserted into the database…

---

<div class="post-metadata">

**Author:** ![Wishka](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/bb73d2/32.png) [@Wishka](https://www.ruby-forum.com/u/Wishka)\
**Post date:** [May 29, 2020, 12:33pm UTC](https://www.ruby-forum.com/t/how-to-add-several-items-in-shopping-cart-in-rails/259668/3 "2020-05-29T12:33:08Z")

</div>

if add cart in migration table it will will be user parametr and it not connecting with shopping cart

---

<div class="post-metadata">

**Author:** ![SouravGoswami](https://www.ruby-forum.com/user_avatar/www.ruby-forum.com/souravgoswami/32/2543_2.png) [@SouravGoswami](https://www.ruby-forum.com/u/SouravGoswami)\
**Post date:** [May 29, 2020, 4:36pm UTC](https://www.ruby-forum.com/t/how-to-add-several-items-in-shopping-cart-in-rails/259668/4 "2020-05-29T16:36:01Z")

</div>

What if you make a relationship of one user with CartItems? You have the Product model already.

For example, in User model, you write `has_many :cart_items`, and in CartItems, you write `belongs_to :user`. In that way you should be able to fetch the cart information.

The cart could contain an array of string, each string will contain the unique id for the actual product.

For the preview, you will fetch the thumbnail image and the price info for the actual product…

I think that way you will be able to link your cart with the user. Let me try it once!

---

<div class="post-metadata">

**Author:** ![Wishka](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/bb73d2/32.png) [@Wishka](https://www.ruby-forum.com/u/Wishka)\
**Post date:** [May 29, 2020, 5:24pm UTC](https://www.ruby-forum.com/t/how-to-add-several-items-in-shopping-cart-in-rails/259668/5 "2020-05-29T17:24:41Z")

</div>

Yes, i don’t mind. [GitHub - wishka/LDC-task: &nbsp;Lunches&nbsp;Delivery&nbsp;Company task](https://github.com/wishka/LDC-task.git)  
You can try

---

<div class="post-metadata">

**Author:** ![Morton](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/f4b2a3/32.png) [@Morton](https://www.ruby-forum.com/u/Morton)\
**Post date:** [June 2, 2020, 6:13am UTC](https://www.ruby-forum.com/t/how-to-add-several-items-in-shopping-cart-in-rails/259668/6 "2020-06-02T06:13:48Z")

</div>

Because a client should be able add products to the cart and have his products in his cart even after he leaves and comes back later we need a way to figure out whether he already has a cart or not [mcdvoice login](https://mcdvoice.me/)

---

<div class="post-metadata">

**Author:** ![SouravGoswami](https://www.ruby-forum.com/user_avatar/www.ruby-forum.com/souravgoswami/32/2543_2.png) [@SouravGoswami](https://www.ruby-forum.com/u/SouravGoswami)\
**Post date:** [June 24, 2020, 9:28pm UTC](https://www.ruby-forum.com/t/how-to-add-several-items-in-shopping-cart-in-rails/259668/7 "2020-06-24T21:28:12Z")

</div>

Ok so replying again after a month! I had to make one shopping app for our college’s major project, I did implement the cart and it works just fine.

I have named cart\_item as line\_item, and stayed with that.

Here’s what I did:

1. I already had a controller for Product and devise User.
2. Created a controller called line\_items, which

```auto
belongs_to :product
belongs_to :user

```

Then in the product and user models, I have:

```auto
has_many :line_items

```

1. In the Product controller, I have a method, that accepts a PATCH request, it adds products to the line\_items, and in respond to block, using ajax, it shows a notification (totally made from scratch by me):

```auto
	def add_to_line_items
		if current_user.is_a?(GuestUser) # Using petergate gem for the authorization, and GuestUser is a dummy user who is not logged in.
			respond_to do |format|
				format.js { render 'sign_in_to_continue' }
			end
		else
			@line_item = LineItem.new(user_id: current_user.id, product_id: @product.id)

			respond_to do |format|
				if @line_item.save
					format.js
				else
					format.js { render 'failed_saving_cart_item' }
				end
			end
		end
	end

```

In the app/views/products/add\_to\_line\_items.js.erb, I have:

```auto
notify("<%= @product.title %> added to cart", 'View Cart', "<%= line_items_path %>")

```

This notifies the user, in the similar way, the failed\_saving\_cart\_item has:

```auto
notify("Error: <%= @product.title %> cannot be added to cart!", 'View Product', "<%= product_path %>")

```

* * *

Now this works fine, but I also have wishlist, which belongs to :user, and :product, and :user and :product have has\_many :wishlists.

This requires the user to be logged in, but you can add some code to check if there is any user or not (check current\_user, in my case current\_user.is\_a?(GuestUser) or current\_user.kind\_of?(GuestUser)), based on that, you store the value on session, or db, but if the value is in session, it will get copied to the db and cleared when the user is logged in (account created / logged in).

It works fine for now, you can follow similar steps to make it working for your project…
