Testing a query result

It’s a very basic question, i want just to test if this query did return
any result.

     @BookDetails = Book.find(params[:id])

I tried “nil”, but it seems that even if there isn’t any book with that
id, @BookDetails is != nil.

Help please!

Hi Mahmou,

Mahmou M’hiri wrote:

It’s a very basic question, i want just to test if this
query did return any result.

    @BookDetails = Book.find(params[:id])

I tried “nil”, but it seems that even if there isn’t any
book with that id, @BookDetails is != nil.

It should be nil if there’s no record in the Books table with that id.
One
thing you might want to do, though, is use:
Book.find(params[:id].to_i) since params are always strings. Other than
that, you’ll need to provide more info.

hth,
Bill

Bill W. wrote:

Hi Mahmou,

Mahmou M’hiri wrote:

It’s a very basic question, i want just to test if this
query did return any result.

    @BookDetails = Book.find(params[:id])

I tried “nil”, but it seems that even if there isn’t any
book with that id, @BookDetails is != nil.

It should be nil if there’s no record in the Books table with that id.
One
thing you might want to do, though, is use:
Book.find(params[:id].to_i) since params are always strings. Other than
that, you’ll need to provide more info.

hth,
Bill

Strings are no problem for ActiveRecord finders.

You Book.find(some_id) should raise an exception if there is no record.
And Book.find_by_id(some_id) should return nil if no record is found.

Try this:

begin
Book.find(params[:id])
rescue ActiveRecord::RecordNotFound
puts “Not Found!”
end

The rescue traps the RecordNotFound exception and lets you do something
if it happens.