Alb
Alb

Reputation: 221

rails cart id show issue

I cannot get my cart icon to link to the user's actual cart without plugging the exact numerical id in. Here is my code that I want to link to a display of the user's cart:

<li class="navtxt"id='cart-button'><%= link_to(image_tag("cart.png"),@cart)%></li>

And at the moment, all it does is flash the screen momentarily and bring me back to the top of the homepage.

My carts controller show begins with:

def show
 begin
  @cart = Cart.find(params[:id])

With a CurrentCart method in my application controller, which is included in my carts controller:

 private

 def current_cart 
   Cart.find(session[:cart_id])
 rescue ActiveRecord::RecordNotFound
   cart = Cart.create
   session[:cart_id] = cart.id
   cart
 end

and

resources :carts

in routes.rb

Any insight? Thanks. I have this open, so if there's any code that can help lead to a solution I'll be immediate with it.

Edit- added preceding code

class CartsController < ApplicationController
  include CurrentCart
  before_action :set_cart, only: [:show, :edit, :update, :destroy]
  rescue_from ActiveRecord::RecordNotFound, with: :invalid_cart
# GET /carts/1
# GET /carts/1.xml 

Upvotes: 1

Views: 221

Answers (1)

Mandeep
Mandeep

Reputation: 9173

Try this:

<li class="navtxt"id='cart-button'>
  <%= link_to @cart do %>
    <%= image_tag("cart.png") %>
  <% end %>
</li>

and since you want to show your cart in navigation so it'll be better to set in application controller. You can do it by:

before_filter :set_cart 

def set_cart 
  @cart = current_cart 
end

Upvotes: 1

Related Questions