Reputation: 3168
I'm trying to integrate eCommerce functionality into my rails app, and am having trouble creating a new order. I start with a cart, which has_many orders, which has_many transactions. The first field in my order database is cart_id. I need to be able to access information in the cart (such as total_price) from the view/order/new.html.erb.
Where would be the best place to build this relation, and how? I can find the cart through the session id, but I don't know how to build the relationship. I was thinking in the order model, in the new action, somthing like so?
def new
@order = Order.new
[email protected]
Defined in my application controller is the function current_cart
def current_cart
Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
cart = Cart.create
session[:cart_id] = cart.id
cart
end
UPDATE
Here is my new and create function, and where I need the value
def new
@order = Order.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @order }
end
end
# POST /orders
# POST /orders.json
def create
@order = Order.new(params[:order])
# THIS IS WHERE I HAVE TRIED TO BUILD THE RELATIONSHIP
# I have tried current_cart.orders.build, @order.cart = current_cart, and
# @order = current_cart.build_order(params[:order])
@order.ip_address = request.remote_ip
if @order.save
if @order.purchase
render :action => "success"
else
render :action => "failure"
end
else
render :action => 'new'
end
end
and this is where I need to access the cart in the model
def price_in_cents
(cart.total_price*100).round
end
And I always get an exception caught for an undefined function, either the build function, or the total price function
Upvotes: 0
Views: 1204
Reputation: 168
In your create action:
@order = current_cart.build_order(order_params)
and add strong params:
private
def order_params
params.require(:order).permit(:first_name, :last_name, :card_type, :card_expires_on)
end
Upvotes: 0
Reputation: 2230
I made a video about this: http://www.ror-e.com/info/videos/6
I actually separate the cart from the order. So basically The cart has_many cart_item and the order has_many order_items. I'd love to help out more. Feel free to contact me directly. I'd love to discuss the pro's & con's of different approaches.
Upvotes: 1
Reputation: 3182
In the Order model you have the cart_id, so define the relation there:
belongs_to :cart
You can also define the relation in the Cart model, additionally:
has_many :orders
After that you can simply add new orders to your current basket:
@order = Order.new
@order.cart = current_cart
EDIT:
Maybe there is an other Problem with the current_cart method.
Try:
@order.cart_id = session[:cart_id]
Upvotes: 3