Jump to content

The ultimate community for Ruby on Rails developers.


Photo

Handling multiple carts in rails

cart order guest session muliple carts

  • Please log in to reply
No replies to this topic

#1 Kloot

Kloot

    Passenger

  • Members
  • 1 posts

Posted 18 August 2014 - 05:01 PM

I'm wondering if there is a shorter solution for my problem.

I'm currently building a multiple shop system, which means a website with different shops where you have 1 open cart for each shop.

This cart can be owned from a guest or a user.

The cart/order should only be created when an item is added.

The following definition is placed in the application controller.

def find_order_by_shop(shop)
shop = Shop.find(shop.to_i) if !(shop.class == Shop)
if session["order_id_for_shop_#{shop.try(:id)}"]
order = Order.find_by_id_and_state(session["order_id_for_shop_#{shop.id}"],'open')
if order
if current_user
current_user.orders.where(:shop_id => shop.id , :state => 'open').where.not(:id => session["order_id_for_shop_#{shop.id}"]).delete_all
order.update_attribute(:user_id, current_user.id)
order = current_user.orders.where(:shop_id => shop.id , :state => 'open').first
if order
# delete all exept first
current_user.orders.where(:shop_id => shop.id , :state => 'open').where.not(:id => order.id).delete_all
else
# create new
order = current_user.orders.new(:shop_id => shop.id , :state => 'open')
end
end
else
order = Order.new(:shop_id => shop.id, :state => 'open')
end
else
if current_user
order = current_user.orders.where(:shop_id => shop.id , :state => 'open').first
if order
current_user.orders.where(:shop_id => shop.id , :state => 'open').where.not(:id => order.id).delete_all
else
order = current_user.orders.new(:shop_id => shop.id , :state => 'open')
end
else
# guest
order = Order.new(:shop_id => shop.id , :state => 'open')
end
end

session["order_id_for_shop_#{shop.try(:id)}"] = order.id
return order
end

Updating the session while adding an item to the cart/order

...
def create # add item to order
@order = find_order_by_shop(params[:shop_id].to_i)
@order.save # save cart
session["order_id_for_shop_#{params[:shop_id]}"] = @order.id
...

This doesn't seem to be the correct rails way.

Any suggestions ?







Also tagged with one or more of these keywords: cart, order, guest, session, muliple, carts

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users