首页 > 解决方案 > Posts#index 中的 NameError(未定义局部变量或方法 `post' 用于未定义局部变量或方法 `post' 用于 #<#:0xc568590>

问题描述

我在我的 Rails 应用程序中收到此错误 =>

#<#:0xc568590> 的未定义局部变量或方法 `post'

我正在使用 ruby​​ 2.3 和 rails 5.2,这里是代码 Index.html.haml

- @posts.each do |post|
  =link_to (image_tag post.image.url(:small))
  %h2= link_to post.title, post
%p
  = post.comments.count
  Comments

= link_to "Add New Inspiration", new_post_path

错误出现在 = post.comments.count

这是我的后控制器

class PostsController < ApplicationController
    before_action :find_post, only: [:show, :edit, :update, :destroy]
    before_action :authenticate_user!, except: [:index, :show]

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

    def show
        @comments = Comment.where(post_id: @post)
    end
    def new
        @post = current_user.posts.build
    end
    def create
        @post = current_user.posts.build(post_params)

        if @post.save
            redirect_to @post
        else
            render 'new'
        end
    end
    def edit

    end
    def update
        if @post.update(post_params)
            redirect_to @post
        else
            render 'edit'
        end
    end
    def destroy
        @post.destroy
        redirect_to root_path
    end

    private

    def find_post
        @post = Post.find(params[:id])
    end
    def post_params
        params.require(:post).permit(:title, :link, :description,:image)
    end
end

标签: ruby-on-railsruby

解决方案


是缩进问题。试试下面

- @posts.each do |post|
  =link_to (image_tag post.image.url(:small))
  %h2= link_to post.title, post
  %p
    = post.comments.count
    Comments

  = link_to "Add New Inspiration", new_post_path

推荐阅读