Admin::Posts#索引中的NoMethodError



我的帖子代码有问题,请看这个。错误是说

管理员中的NoMethodError::Posts#index正在显示/home/muba/rblog/app/views/admin/posts/index.html.erb其中第2行引发:

未定义的方法"存在吗?"对于零:NilClass

post>index.html.erb在这里:

            <h2 class="page-header">Posts <%= link_to "Create New", new_admin_post_path, class:'btn btn-success pull-right' %></h2>
         <% if @posts.exists? %>
        <table class="table table-striped">
          <tr>
            <th>Post Title </th>
            <th>Date Created</th>
            <th>Post Category </th>
            <th> Actions </th>
          </tr>
          <% @posts.each do |post|  %>
          <tr>
            <td><%= post.title %></td>
            <td><%= post.created_at.to_time.strftime('%B %e at %l:%M %p') %></td>
            <td><%= post.category.name %></td>
            <td><%= link_to "Edit", edit_admin_post_path(post), class:'btn btn-primary' %> <%= link_to "Delete", admin_posts_path(post), class:'btn btn-danger', method: :delete, data: {confirm: 'Are you sure'} %></td>
          </tr>
          <% end %>
        </table>
        <%= will_paginate @posts %>
        <% else %>
        <p> There are no posts </p>
        <% end %>

邮局管理员是:

class PostsController < ApplicationController
def new
@page_title = 'Add Post'
@post = Post.new
end
def create
@post = post.new(post_params)
if @post.save
  flash[:notice] = 'Post Created'
  redirect_to admin_posts_path
else
  render 'new'
end
end
def edit
@post = Post.find(params[:id])
end
def update
 @post = Post.find(params[:id])
 if @post.update(post_params)
  flash[:notice] = 'Post Updated'
  redirect_to admin_posts_path
else
  render 'new'
end
end
def destroy
    @post = Post.find(params[:id])
    @post.destroy
     flash[:notice] = 'Post Removed'
end
def index
@posts = Post.all
end
private
def category_params
params.require(:post).permit(:title, :category_id, :user_id, :tags, :image, :body)
end

请给我一个解决方案:(

检查如下帖子:-

<% if @posts.present? %>
<% end %>

可能是这样的:

<% unless @posts.nil? %>

根据文档,exists?通常用于比较,使用参数来检查是否存在。

您也可以尝试以下操作:

<% if !@posts.nil? %>   
    <%= your code... %>
<% end %>

这也将有助于你的事业。

最新更新