Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails - has_one relation, how to check if it has an existing association?

I have a simple problem, related to associations. I have a model for book, that has_one reservation. Reservation belongs_to book.

I want to make sure in the create method of reservations controller that a book is not reserved already when a reservation is made. In other words, I need to check if any other reservation exists for that book. How do i do that?

EDIT: Aaaand i made it, thanks everyone for the tips, learned some new stuff. When i tried offered solutions, I got no_method errors, or nil_class etc. That got me thinking, that the objects I'm trying to work on simply don't exist. Krule gave me the idea to use book.find, so i tried working with that. Ultimately i got it working with:

book=Book.find_by_id(reservation_params[:book_id])
unless book.is_reserved?

Thanks everybody for your anwsers, I know it's basic stuff but i learned a lot. Cheers!

like image 998
Looted Avatar asked Dec 30 '13 22:12

Looted


2 Answers

How about:

self.reservation.present?

This should return true if an association exists.

like image 169
Matthias Avatar answered Oct 09 '22 20:10

Matthias


Little bit performance gain can be obtained if you use

#app/models/book.rb
def is_reserved?
  Reservation.exists?(book_id: id)
end

#somewhere else
book = Book.find(id)
book.is_reserved?
like image 28
Haseeb A Avatar answered Oct 09 '22 20:10

Haseeb A