Forum: Ruby Testing a query result

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.
Mahmoud M. (Guest)
on 2007-02-24 20:28
Hello every body,

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!
Gavin K. (Guest)
on 2007-02-24 20:56
(Received via mailing list)
On Feb 24, 11:28 am, Mahmou M'hiri <removed_email_address@domain.invalid> wrote:
> It's a very basic question, i want just to test if this query did return
> any result.
>
>          @BookDetails = Book.find(params[:id])

You will probably get better results asking this question on the Ruby
on Rails discussion forum. You have instead asked it on the ruby-talk
mailing list.
Mahmoud M. (Guest)
on 2007-02-24 21:11
that's true!
Stefan M. (Guest)
on 2007-02-25 02:09
(Received via mailing list)
Phrogz wrote:
> On Feb 24, 11:28 am, Mahmou M'hiri <removed_email_address@domain.invalid> wrote:
>> It's a very basic question, i want just to test if this query did return
>> any result.
>>
>>          @BookDetails = Book.find(params[:id])
>
> You will probably get better results asking this question on the Ruby
> on Rails discussion forum. You have instead asked it on the ruby-talk
> mailing list.

I actually think that this is an ActiveRecord question. Does this
qualify for a redirect to rails (even if params[:id] is a good hint)?

I have to admit that I do not know whether rails does change this
behaviour.

Do we cover ActiveRecord questions on ruby-talk?


To answer the original question:

ActiveRecord will raise an ActiveRecord::RecordNotFound exception which
you can detect/catch via

begin
  @BookDetails = Book.find(params[:id])
rescue ActiveRecord::RecordNotFound
  # the query did not return a result
end

Stefan
Jason Palmer (Guest)
on 2007-02-25 04:52
(Received via mailing list)
The easiest way to do this is using the exists? function.
Example:

if Book.exists?(params[:id])
   @BookDetails = Book.find(params[:id])
else
  #No results
end
This topic is locked and can not be replied to.