Skip to content

Instantly share code, notes, and snippets.

@rocodev-tech
rocodev-tech / _navbar.html.erb
Created June 12, 2014 21:16
app/views/common/_navbar.html.erb
<ul class="nav navbar-nav navbar-right">
<li>
<%= link_to "#" do %>
購物車 <i class="glyphicon glyphicon-shopping-cart"> </i> (0)
<% end %>
</li>
<% if !current_user %>
<li> <%= link_to("登入", new_user_session_path) %> </li>
@rocodev-tech
rocodev-tech / show.html.erb
Created June 12, 2014 21:37
app/views/product/show.html.erb
<div> 數量 : <%= render_product_quantity(@product) %> </div>
<div class="product-price"> $ <%= render_product_price(@product) %> </div>
<div class="pull-right">
<%= link_to("加入購物車", add_to_cart_product_path(@product) , :method => :post , :class => "btn btn-primary btn-lg btn-danger") %>
</div>
@rocodev-tech
rocodev-tech / routes.rb
Created June 12, 2014 21:39
config/routes.rb
resources :products do
member do
post :add_to_cart
end
end
@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
@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 / 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 / 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 / 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 / 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 / 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