0

I am having problem with my post code please see this. The error is saying

NoMethodError in Admin::Posts#index Showing /home/muba/rblog/app/views/admin/posts/index.html.erb where line #2 raised:

undefined method `exists?' for nil:NilClass

post> index.html.erb is here:

            <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 %>

And The Posts Controller is:

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

Please give me a solution :(

Dasrath
  • 366
  • 2
  • 11

3 Answers3

0

Check @post like this:-

<% if @posts.present? %>
<% end %>
user3506853
  • 814
  • 5
  • 3
  • welcome.. :) Please see this link http://stackoverflow.com/questions/13186722/what-is-the-difference-between-using-exists-and-present-in-ruby – user3506853 Dec 03 '15 at 09:57
0

May be this works:

<% unless @posts.nil? %>

As per the documentation, exists? generally used for comparison, takes argument to check whether exist or not.

Dusht
  • 4,712
  • 3
  • 18
  • 24
0

You can also try this :

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

This will also help your cause .