Forum: Ruby on Rails .empty? Method

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
2d66c63b4d8193d0279bd18200e109d3?d=identicon&s=25 Michael Boutros (michaelboutros)
on 2006-02-12 02:31
I am using:

    if @post.empty?
       render_text "Post does not exist."
    end

But it gives me this error:

NoMethodError in Posts#view

undefined method `empty?' for #<Posts:0x39598d0>

However, if the method list empty? apears and stuff so I am confused.
Cb610750ee94ca103aef4b2dc7b1b768?d=identicon&s=25 Nick Stuart (Guest)
on 2006-02-12 02:46
(Received via mailing list)
It looks like you are calling it on a Post object, where the .empty is
meant for collections/strings and such. Should the above line read,
if @posts.empty?
..

Notice the s. I'm guessing you are loading posts like:
@posts = Post.find(:all)?

if so then @posts.empty? should work just fine.

-Nick
2d66c63b4d8193d0279bd18200e109d3?d=identicon&s=25 Michael Boutros (michaelboutros)
on 2006-02-12 02:52
Nick Stuart wrote:
> It looks like you are calling it on a Post object, where the .empty is
> meant for collections/strings and such. Should the above line read,
> if @posts.empty?
> ..
>
> Notice the s. I'm guessing you are loading posts like:
> @posts = Post.find(:all)?
>
> if so then @posts.empty? should work just fine.
>
> -Nick

No, I am doing a view page to view an entry seperately. I am using the
.empty? method to check if the row exists, and if it does not I will
output an error. This is the entire page code:

class PostsController < ApplicationController
  def index
    @posts = Posts.find_all
  end

  def view
    @post = Posts.find(@params["id"])

    if @post.empty?
       render_text "Post does not exist."
    end

  end

end
7c4087d053eb02d099a17d91ba5e33b5?d=identicon&s=25 Brian V. Hughes (Guest)
on 2006-02-12 03:14
(Received via mailing list)
Michael Boutros wrote:
>   def view
>     @post = Posts.find(@params["id"])
>     if @post.empty?
>        render_text "Post does not exist."
>     end
>   end

You can't use empty? on a class object. That method isn't supported,
which i
believe is exactly what the error message tried to tell you. You want to
check
to see if the result of the find command has resulted in a defined @post
object.

Change the condition to: if @post.nil?

or: unless @post

-Brian
This topic is locked and can not be replied to.