Em Sta
Em Sta

Reputation: 1706

Rails display simple partial?

My steps so far: Ive created an new rails app:

rails new sample

cd sample

rails g scaffold Post name:string content:string

rails g controller welcome home

Next step i added to the welcome/home view one line:

<h1>Welcome#home</h1>
<p>Find me in app/views/welcome/home.html.erb</p>
<%= render "posts/index" %>

Then i copied the code form post/index to post/_index.html.erb

But somehow my partial wont work in welcome/home, my error:

NoMethodError in Welcome#home

Showing C:/Sites/sample/app/views/posts/_index.html.erb where line #12 raised:

undefined method `each' for nil:NilClass
Extracted source (around line #12):

9:     <th></th>
10:   </tr>
11: 
12: <% @posts.each do |post| %>
13:   <tr>
14:     <td><%= post.name %></td>
15:     <td><%= post.content %></td>

SO what did i wrong?

Upvotes: 0

Views: 62

Answers (2)

dariodaic
dariodaic

Reputation: 71

If you do not really need a welcome controller you can keep @posts from posts#index and show another template in the same step using render:

class PostsController < ApplicationController
def index
@posts = Post.all
render 'home'
end
...

You put home.html.erb inside 'views/posts' directory. If a template you want to render is in 'views/some_other_directory' you can use:
render :file => 'controller_name/template_name'

Upvotes: 1

Richard
Richard

Reputation: 4067

You need to define @posts in your controller:

@posts = Post.all

Upvotes: 1

Related Questions