Forum: Ruby on Rails find() and has_many

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.
sirdavidoff (Guest)
on 2005-12-17 17:42
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.
sirdavidoff (Guest)
on 2005-12-17 17:48
Sorry guys, I am a fool ;)

find(:first) returns nil instead of throwing an exception when nothing
is found.
This topic is locked and can not be replied to.