EggSix
EggSix

Reputation: 988

No Method Error on .each What am I missing?

I'm trying to have my carousel and index rendered on the home page. I'm getting a no method error on my .each loop but I can't seem to track down the problem. Here is my code please help =/. Everything looks right to me as I am following a fairly recent tutorial.

Showing /Users/prestonphan/Desktop/My_Portfolio/app/views/posts/_index.html.erb where line #1 raised:

posts_controller.rb

class PostsController < ApplicationController

    def index  
        @posts = Post.all.order('created_at DESC')
    end

    def new
    end

    def create
        @post = Post.new(post_params)
        @post.save
        redirect_to @post
    end

    def show
        @post = Post.find(params[:id])
    end

    private
    def post_params
        params.require(:post).permit(:title, :content)
    end
end

_index.html.erb

<% @posts.each do |post| %>
    <div class="post_wrapper">
        <h2 class="title"><%= link_to post.title, post %></h2>
        <p class="date"><%= post.created_at.strftime['%B, %d, %Y']%></p>
    </div>
<% end %>

home.html.erb

<div class="jumbotron center">
    <h1>Eggsix</h1>
    <p>dozens by the half</p>
</div>
<%= render 'static_pages/carousel'%>
<%= render 'posts/index'%>

https://github.com/Eggsix/Half_dozen_full

Upvotes: 0

Views: 355

Answers (1)

Rustam Gasanov
Rustam Gasanov

Reputation: 15791

If you want to re-use some view, make a partial like this(it is more convenient to add partials like _post.html.erb to render a single item, but for your understanding I made solution simplier):

app/views/posts/_posts.html.erb

<% posts.each do |post| %>
  <div class="post_wrapper">
    <h2 class="title"><%= link_to post.title, post %></h2>
    <p class="date"><%= post.created_at.strftime['%B, %d, %Y']%></p>
  </div>
<% end %>

Then, in app/views/posts/index.html.erb just call partial render, providing a collection of posts:

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

Same for app/views/static_pages/home.html.erb, add:

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

But your @posts variable is nil for home view case, so you should fetch posts in home action of your StaticPagesController too:

class StaticPagesController < ApplicationController
  def home
    @posts = Post.all.order('created_at DESC')
  end
end

Thats it. Hope this makes sense to you.

Upvotes: 1

Related Questions