Search code examples
ruby-on-railsrubye-commerce

Linking to basket/cart in ruby on rails


I have a menu in my header that has a show basket and a login button, each work when the code is placed in separately but not when both lines are in the file. I'm using devise for the users. Is there a better way to link to the current basket?

<li><%= link_to basket_path(@basket.id) do %>
  <%= image_tag "/assets/viewBasket.png" %>
</li>
<% end %>
<% if signed_in? %>
  <li><%= link_to edit_user_registration_path do%>
    <%= image_tag"/assets/my_account.png" %></a></li>
  <% end %>
  <li><%= link_to destroy_user_session_path do%>
    <%= image_tag"/assets/logout.png" %></li>
  <%end%>
<% else %>
  <li><%= link_to new_user_session_path do%>
    <%= image_tag"/assets/loginRegisterBtn.png" %></li>
  <% end%>
<% end %>

If I run on its own this works but not with the code after.

<li><%= link_to basket_path(@basket.id) do %>
  <%= image_tag "/assets/viewBasket.png" %></li>
<% end %>

I think its to do with the way the current basket is set with the session id in the current_basket model.

module CurrentBasket
private 
  def set_basket
    @basket = Basket.find(session[:basket_id])
    rescue ActiveRecord::RecordNotFound
    @basket = Basket.create
    session[:basket_id] = @basket.id
  end
end

Solution

  • I used the answer above which helped with one issue, however, I found that I had defined only the shop and index page. Removing this and it now works.

     include CurrentBasket
     before_action :set_basket, only: [:index, :shop]