Skip to content

Instantly share code, notes, and snippets.

@rocodev-tech
rocodev-tech / create_order_item.rb
Created June 13, 2014 04:00
create_order_item.rb
class CreateOrderItems < ActiveRecord::Migration
def change
create_table :order_items do |t|
t.string :product_name
t.float :price
t.integer :quantity
t.integer :order_id
t.timestamps
end
end
@rocodev-tech
rocodev-tech / create_order_info.rb
Created June 13, 2014 04:00
create_order_info.rb
class CreateOrderInfos < ActiveRecord::Migration
def change
create_table :order_infos do |t|
t.integer :order_id
t.string :billing_name
t.string :billing_address
t.string :shipping_name
t.string :shipping_address
t.timestamps
@rocodev-tech
rocodev-tech / create_order.rb
Last active August 29, 2015 14:02
create_order.rb
class CreateOrders < ActiveRecord::Migration
def change
create_table :orders do |t|
t.integer :user_id
t.integer :total
t.boolean :paid, :default => false
t.timestamps
end
end
end
@rocodev-tech
rocodev-tech / carts_controller.rb
Created June 13, 2014 03:58
app/controllers/carts_controller.rb
class CartsController < ApplicationController
before_action :authenticate_user!, :only => [:checkout]
def index
end
def checkout
@order = current_user.orders.build
@info = @order.build_info
@rocodev-tech
rocodev-tech / checkout.html.erb
Last active August 29, 2015 14:02
app/views/carts/checkout.html.erb
<div class="row">
<div class="col-md-12">
<h2> 購物明細 </h2>
<table class="table table-bordered">
<thead>
<tr>
<th width="80%">商品明細</th>
<th>單價</th>
@rocodev-tech
rocodev-tech / index.html.erb
Last active August 29, 2015 14:02
app/views/carts/index.html.erb
<div class="row">
<div class="col-md-12">
<h2> 購物車 </h2>
<table class="table table-bordered">
<thead>
<tr>
<th>商品資訊</th>
<th></th>
@rocodev-tech
rocodev-tech / cart_item.rb
Created June 12, 2014 22:05
app/models/cart_item.rb
class CartItem < ActiveRecord::Base
belongs_to :cart
belongs_to :product
end
@rocodev-tech
rocodev-tech / cart.rb
Created June 12, 2014 22:05
app/models/cart.rb
class Cart < ActiveRecord::Base
has_many :cart_items, :dependent => :destroy
has_many :items, :through => :cart_items, :source => :product
def add_product_to_cart(product)
items << product
end
@rocodev-tech
rocodev-tech / application_controller.rb
Created June 12, 2014 22:04
app/controllers/application_controller.rb
helper_method :current_cart
def current_cart
@current_cart ||= find_cart
end
def find_cart
cart = Cart.find_by(id: session[:cart_id])
@rocodev-tech
rocodev-tech / products_controller.rb
Created June 12, 2014 22:02
app/controllers/products_controller.rb
def add_to_cart
@product = Product.find(params[:id])
if !current_cart.items.include?(@product)
current_cart.add_product_to_cart(@product)
flash[:notice] = "你已成功將 #{@product.title} 加入購物車"
else
flash[:warning] = "你的購物車內已有此物品"
end