How to add several items in shopping cart in rails?

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:

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:

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

product/show/html.erb

<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>

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…

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

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!

Yes, i don’t mind. https://github.com/wishka/LDC-task.git
You can try

1 Like

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

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
belongs_to :product
belongs_to :user

Then in the product and user models, I have:

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):
	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:

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:

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…

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs