**我为发布创建了控制器和模型,但无法显示发布的 显示页面上的标题,但反复出现相同的错误**
my posts_controller code :
class PostsController < ApplicationController
def index
end
def new
end
def create
#render plain: params[:post][:body].inspect
@post = Post.new(post_params)
if @post.save
redirect_to posts_path
else
render "new"
end
end
def show
@post= Post.find(:id=>params[:id])
# @article = "prateek"
end
private
def post_params
params.require(:post).permit(:title,:body)
end
end
我的show.html.erb文件:
<h1><%= @post.title %></h1>
我的post.rb文件:
class Post < ApplicationRecord
end
**I expect the result but I didn't get anything right
error = NoMethodError in Posts#show
undefined method `title' for nil:NilClass**
答案 0 :(得分:2)
您正在将哈希传递给find
,而您只想传递ID。
@post= Post.find(params[:id])
或如果您想传递哈希值,请使用find_by
@post= Post.find_by(:id => params[:id])