Marko I. Marko I. - 5 months ago 29
Ruby Question

How to keep same order on each session?

I'm working on a store in rails. As I'm new to Rails I was following some tutorial on how to create a shopping cart and ordering system.

So right now orders with unique ids are being created and saved by a user, automatically, upon addition of a order_item to a cart on each new session. And this is the issue.

I want order to persist until 30 days passes (the one order that is created first, that is, when first order_item has been added by a user). The problem is next: So if user adds order_items, he creates an order and then logs out and comes back and adds a new order_item to his cart, new order is being created even though there is already his older order saved to database. I want to retrieve that first order.

Can you please tell me how to achieve this?

class OrderItemsController < ApplicationController
def create
@order = current_order
@order_item = @order.order_items.new(order_item_params)
@order.user_id = current_user.id
@order.save
session[:order_id] = @order.id

respond_to do |format|
format.js { flash[:notice] = "ORDER ITEM HAS BEEN ADDED." }
end
end


order_item.rb

class OrderItem < ActiveRecord::Base
belongs_to :product
belongs_to :order
validates_associated :order
validates :quantity, presence: true, numericality: { only_integer: true, greater_than: 0 }
validate :product_present
validate :order_present


before_save :finalize

def unit_price
if persisted?
self[:unit_price]
else
product.price
end
end

def total_price
unit_price * quantity
end

private
def product_present
if product.nil?
errors.add(:product, "is not valid or is not active.")
end
end

def order_present
if order.nil?
errors.add(:order, "is not a valid order.")
end
end

def finalize
self[:unit_price] = unit_price
self[:total_price] = quantity * self[:unit_price]
end


end


order.rb

class Order < ActiveRecord::Base
belongs_to :order_status
belongs_to :user
has_many :order_items
validates_length_of :order_items, maximum: 3
before_create :set_order_status
before_save :update_subtotal



def subtotal
order_items.collect { |oi| oi.valid? ? (oi.quantity * oi.unit_price) : 0 }.sum
end
private
def set_order_status
self.order_status_id = 1
end

def update_subtotal
self[:subtotal] = subtotal
end



end


user.rb

has_many :order

Answer

I want to retrieve that first order.

This line:

@order = current_order

Where is current_order defined? You want it to find the existing order if present, instead of creating a new one. Something like:

 def current_order
    order = Order.find_by_user_id(current_user.id)
    if order.nil?
       order = Order.create (...etc)
    end
    order
 end
Comments