I have a user model which has these columns - name, email, books_on_loan
I have a booking system where users can check out/in books. When A user checks a book out I want to increase their 'books_on_loan_ integer by one, and vice versa.
So far I have tried it like this and am getting an error "undefined method `+' for nil:NilClass" - it doesnt like the @user.books_on_loan
def check_out
@params = params[:book]
title = @params[:title]
name = @params[:name]
@book = Book.find_by_title(title)
@user = User.find_by_name(name)
if @user == nil
@note = 'This user is not registered.'
elsif @book == nil
@note = 'This book is not in the library.'
elsif @book.onloan == 1
@note = 'This book is on loan.'
elsif @user.books_on_loan == 3
@note = 'This user already has 3 books out.'
else
@book.onloan = 1
@book.save
@books_loaned = BooksOnloan.create(book_id: @book.id, user_id: @user.id)
@books_loaned.save
@user.books_on_loan = @user.books_on_loan + 1
@user.save
@note = 'The book was checked out.'
end
respond_to do |format|
format.html
end
end
Try this:
@user.increment :books_on_loan, 1
You can try with following codes, that will handle nil value for @user.books_on_loan
@user.books_on_loan = @user.books_on_loan.to_i + 1
or
@user.books_on_loan = (@user.books_on_loan || 0) + 1
or
@user.books_on_loan = (@user.books_on_loan.present? ? @user.books_on_loan : 0) + 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With