S
S
ssh02010-11-06 21:57:49
Ruby on Rails
ssh0, 2010-11-06 21:57:49

Ruby on Rails: render - display menu, cart on every page of the site?

Good evening! Interested in the following question, how to add a shopping cart for an online store to each page of the site (basket as in the Agile Web Dev book), I have 4 models - Category, Product, Cart, Post.
layout application.html.erb

<%= render :partial => 'categories/cart', :locals => {:cart => @cart}%>

partial_cart.html.erb _
&lt;% if @cart.blank? %&gt;<br/>
&lt;% else %&gt;<br/>
 &lt;% for item in @cart.items %&gt;<br/>
 &lt;%= item.quantity %&gt; × &lt;%=h item.title %&gt;&lt;%= number_to_currency(item.price) %&gt;<br/>
 &lt;% end %&gt;<br/>
Итого: &lt;%= number_to_currency(@cart.total_price) %&gt;<br/>
 &lt;%= button_to 'Очистить корзину', :controller =&gt; 'categories', :action =&gt; 'empty_cart'%&gt;<br/>
&lt;% end %&gt;

In this scenario, the cart is displayed only in the view of the Categories controller. I can’t figure out how to get the necessary data from the session[:cart] session or in some other way.
And another question, how to properly display the menu on each page, now something like this:
&lt;%= render :partial =&gt; 'posts/post', :collections =&gt; Post.all %&gt;

Thanks for answers.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
kirsan_vlz, 2010-11-06
@kirsan_vlz

If you cannot get the cart from the session, then take a closer look in the book where you took the cart from, find_cart method:

def find_cart
    session[:cart] ||= Cart.new
end

If the problem is simply that the cart object is assigned to the @cart variable in all templates, then move the find_cart method to the application_controller.rb file and include this method in before_filter in the same file. Then your cart will be unloaded from the session into the @cart variable in all controllers.
ps Do not copy the HTML code directly, the parser ate half of the code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question