.each没有方法错误我缺少什么?

时间:2014-12-21 08:38:02

标签: ruby-on-rails ruby ruby-on-rails-4

我试图在主页上显示我的轮播和索引。我在我的.each循环中遇到了无方法错误,但我似乎无法追查问题。这是我的代码请帮助= /。当我遵循最近的教程时,一切看起来都是正确的。

显示/Users/prestonphan/Desktop/My_Portfolio/app/views/posts/_index.html.erb第1行:

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

1 个答案:

答案 0 :(得分:1)

如果你想重新使用一些视图,那就做一个像这样的部分(添加像_post.html.erb这样的部分来渲染单个项目会更方便,但为了你的理解,我让解决方案更简单了):

应用/视图/帖/ _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 %>

然后,在 app / views / posts / index.html.erb 中,只需调用部分渲染,提供一系列帖子:

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

app / views / static_pages / home.html.erb 相同,请添加:

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

@postsnil变量的home变量为home,因此您应该在StaticPagesController的{​​{1}}行动中获取帖子:

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

多数民众赞成。希望这对你有意义。