4thSpace
4thSpace

Reputation: 44312

How to render partial view?

I have the following:

/controllers/test_controller.rb

/views/test/index.html.erb

/views/test/_partial.html.erb

I want to render the partial in the index view. I'm doing this:

index.html.erb

<h1>Test#index</h1>
<%= render "_partial" %>

_partial.html.erb

<p>This is partial content</p>

When I go to localhost:3000/test/index, I get this error:

ActionView::MissingTemplate in Test#index
Missing partial /__partial with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}.
Extracted source (around line #2):

1 <h1>Test#index</h1>
2 <%= render "_partial" %>

Any idea what I'm doing wrong?

Upvotes: 4

Views: 14875

Answers (3)

Hany Moh.
Hany Moh.

Reputation: 989

You can try this

<% @users.each do |user| %>
        <%= render 'erb_partials/post', user: user %>
    <% end %>

Upvotes: 0

All depends where is your partial. If you have the partial _partial in layouts folder, you only have to do is call the partial like this <%= render "partial" %>.

Rails know that a file with the underscore at the beggining is a partial. So, when you render the partial, you don't have to use the underscore.

Remember, Rails is convention over configuration.

Upvotes: 2

sclem72
sclem72

Reputation: 486

This question has already been answered, but when the partial is in the same directory as your current view, you can just render the partial with no underscore. But if you want to extract a partial from another controller you will need to take it one step back and use a more complete path, like "users/partial".

Upvotes: 5

Related Questions