Uday kumar das
Uday kumar das

Reputation: 91

how to render a _form from another view folder in rails 4.1

In carts/_form:

 <% for item in @cart.line_items %>             
 <%= item.quantity %> &times;<%= item.menu.menu_item_name %>
 <%= item.quantity*item.menu.price%>    
 <% end %>

in menus/index:

 <%= render partial: 'carts/form'%>

I want to show the _form on index page.

Upvotes: 0

Views: 2551

Answers (2)

ArtLion
ArtLion

Reputation: 33

In carts/_form.html.erb :

 <% for item in @cart.line_items %>             
 <%= item.quantity %> &times;<%= item.menu.menu_item_name %>
 <%= item.quantity*item.menu.price%>    
 <% end %>

to use in _form.html.erb in any other *.html.erb put line

<%= render "carts/form" %>

in *.html.erb documents inside carts catalog, you can write simple :

<%= render "form" %>

because it's look for _form.html.erb in present catalog

Upvotes: 0

Peege151
Peege151

Reputation: 1560

The point of partials is to have them as chunks of code that can be used anywhere in your app. Unless I misunderstand your question, might I suggest creating the following directory structure:

app
|-views
   |-cart(or wherever your form currently is)
   |-partials
      |-_partialYouWantToUse.html.erb

This way you can render it using

<%= render "partials/partialYouWantToUse" %>

ANYWHERE you want in your app.

Note you do not use an underscore _ when you are rendering the partial, you only save it with one.

edit as a result of your comment:

You can render a partial from any folder, as long as it's relative to the view folder. so: <%= render "WhateverFolder/evenAnotherFolder/_whateverpartial" %>

As long as whateverFolder is a direct decendent of views.

The partial or layout folder is a rails convention, and helps for people who are looking through your code. It keeps things organized.

Upvotes: 2

Related Questions