Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
implement current_cart function
  • Loading branch information
anndoko committed May 9, 2017
1 parent a423503 commit d273481
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
17 changes: 17 additions & 0 deletions app/controllers/application_controller.rb
Expand Up @@ -5,5 +5,22 @@ def admin_required
if !current_user.admin?
redirect_to "/", alert: "You are not an admin."
end
end

helper_method :current_cart

def current_cart
@current_cart ||= find_cart
end

private

def find_cart
cart = Cart.find_by(id: session[:cart_id])
if cart.blank?
cart = Cart.create
end
session[:cart_id] = cart.id
return cart
end
end
4 changes: 3 additions & 1 deletion app/controllers/products_controller.rb
Expand Up @@ -9,7 +9,9 @@ def show

def add_to_cart
@product = Product.find(params[:id])

current_cart.add_product_to_cart(@product)
flash[:notice] = "成功加入购物车"
redirect_to :back
flash[:notice] = "测试加入购物车"
end
end
7 changes: 7 additions & 0 deletions app/views/common/_navbar.html.erb
Expand Up @@ -13,6 +13,13 @@
</li>
</ul>
<ul class="nav navbar-nav navbar-right">

<li>
<%= link_to "#" do %>
購物車 <i class="fa fa-shopping-cart"> </i> ( <%= current_cart.products.count %> )
<% end %>
</li>

<% if !current_user %>
<li><%= link_to("註冊", new_user_registration_path) %></li>
<li><%= link_to(content_tag(:i, '登入', class: 'fa fa-sign-in'), new_user_session_path) %></li>
Expand Down

0 comments on commit d273481

Please sign in to comment.