【问题标题】:NoMethodError in Admin::Posts#indexAdmin::Posts#index 中的 NoMethodError
【发布时间】:2015-12-03 07:59:47
【问题描述】:

我的邮政编码有问题,请看这个。 错误是说

Admin::Posts#index 显示中的 NoMethodError /home/muba/rblog/app/views/admin/posts/index.html.erb 其中第 2 行 提出:

未定义的方法“存在吗?”对于 nil: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

请给我一个解决方案:(

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    像这样检查@post:-

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

    【讨论】:

    【解决方案2】:

    这可能有效:

    <% unless @posts.nil? %>
    

    根据documentationexists?一般用于比较,带参数检查是否存在。

    【讨论】:

      【解决方案3】:

      你也可以试试这个:

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

      这也将有助于您的事业。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-11-18
        • 1970-01-01
        • 2015-07-09
        • 2014-02-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多