#depot/app/views/carts/_cart.html.erb <h2>Your Cart</h2> <table> <%= render(cart.line_items) %> # как работает? <tr class="total_line"> <td colspan="2">Total</td> <td class="total_cell"><%= number_to_currency(cart.total_price) %></td> </tr> </table> <%= button_to 'Empty cart', cart, method: :delete, data: { confirm: 'Are you sure?' } %> #depot/app/views/line_items/_line_item.html.erb <tr> <td><%= line_item.quantity %>&times;</td> <td><%= line_item.product.title %></td> <td class="item_price"><%= number_to_currency(line_item.total_price) %></td> </tr> 

_cart.html.erb is called from layout: <%= render @cart %>

What happens in this code, how do partial templates work?

    1 answer 1

    When you call render on an ActiveModel compatible object ( one record), it calls the method .to_partial_path . Usually it returns a string like "вещи/вещь" . It works for you for @cart (it probably returns carts/cart ). And draws (renders) it by associating the object being drawn with the variable of the same name (with the template) (you have a cart ).


    With collections, the mechanism works in much the same way , but for its elements , obtained through .each . Just draws them in a row. Your render(cart.line_items) is almost the same as:

     render("line_items/line_item", collection: cart.line_items) 

    ... only what submissions to use, he will find out himself by asking the elements. There is an interesting related trick: it allows you to quickly draw a collection of elements of different types , issuing the appropriate template to each of them.

    • Why is the name _articles.html.erb number _article.html.erb ? guides.rubyonrails.org/… - jisecayeyo
    • one
      @jisecayeyo typo is likely. You can check in yourself. - D-side