ruby-on-rails - 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
解决方案
是缩进问题。试试下面
- @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
推荐阅读
- node.js - 使用代理调用外部 API 的最佳方式
- amazon-web-services - AWS 安全组:入站规则的来源与安全组名称相同吗?
- mysql - 查询以打印来自多个表的数据
- python - 影响文本周围临时框的印刷文本
- tailwind-css - 如何显示项目直到 1 行中的 3 个元素,并且下一个第 4 个元素必须在 tailwindcss 的下一行?
- php - 如何在laravel中用2个不同的关联表示两个模型关系
- sharepoint - 从 SharePoint 库创建缩略图
- python - 如何在lamba和map中使用for循环?
- javascript - React Joyride:步骤跳过,工具提示不显示,重置不起作用
- r - AUC 和 cvAUC 的 mlr3 置信区间