簡體   English   中英

.each沒有方法錯誤我缺少什么?

[英]No Method Error on .each What am I missing?

我正在嘗試在首頁上顯示我的輪播和索引。 我的.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

如果您想重用某些視圖,請像這樣創建局部視圖(添加諸如_post.html.erb類的_post.html.erb以渲染單個項目更為方便,但是為了您的理解,我_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 } %>

但是對於home視圖,您的@posts變量為nil ,因此您也應該在StaticPagesController home操作中獲取帖子:

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

而已。 希望這對您有意義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM