Find() and has_many


#1

Hi guys,

I have two classes, library and book. library has_many :books.

When I want to add a book to a library, I call library.books << book. So
far so good.

However, before I add the book, I need to check whether it’s already in
the library. I thought I would do this by adding ‘unless
library.books.find(book)’, but this doesn’t work because if find()
doesn’t find anything it seems to throw an exception rather than
returning nil.

Can anyone tell me how I can check whether the book is already in the
library?

Thanks!

David.


#2

Sorry guys, I am a fool :wink:

find(:first) returns nil instead of throwing an exception when nothing
is found.