Admin :: Posts#show中的NoMethodError

时间:2016-03-04 21:46:22

标签: ruby-on-rails ruby

我正在尝试将内容添加到“显示”页面,包括标题,内容和发布详细信息。当我从本地主机运行时,我收到以下错误;

Showing /Users/laurenwoodhams/Desktop/PROJECT/RAILS-BLOG/-t/app/views/admin/posts/show.html.erb where line #2 raised:

undefined method `title' for nil:NilClass
<h1>Admin::Posts#show</h1>
<p><b>title:</b> <%= @post.title %></p>
<p><b>content:</b> <%= @post.content %></p>
<p><b>publish:</b> <%= @post.publish %></p>
<p><b>created:</b> <%= @post.created_at %></p>

这是我崇高的Show表单的外观;

<h1>Admin::Posts#show</h1>
<p><b>title:</b> <%= @post.title %></p>
<p><b>content:</b> <%= @post.content %></p>
<p><b>publish:</b> <%= @post.publish %></p>
<p><b>created:</b> <%= @post.created_at %></p>

后控制器;

class Admin::PostsController < Admin::ApplicationController
  def index
    if params[:search].present?
      @posts = Post.matching_title_or_content(params[:search]).page params[:page]
    else
      @posts = Post.all.order(id: :desc).page params[:page]
    end
  end

  def new
  end

  def create
  end

  def edit
  end

  def update
  end

  def show
    @posts = Post.find(params[:id])
  end

  def destroy
  end
end

您能解释一下为什么会出现这种错误吗?

2 个答案:

答案 0 :(得分:0)

您的观点使用@post变量,但在您的展示操作中,您定义了@posts。可能是一个错字。试试:

def show
  @post = Post.find(params[:id])
end

答案 1 :(得分:0)

对于索引方法

  def index
    if params[:search].present?
      @posts = Post.matching_title_or_content(params[:search]).page params[:page]
    else
      @posts = Post.all.order(id: :desc).page params[:page]
    end
  end

显示方法

  def show
    @post = Post.find(params[:id])
  end