Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment/decrement integer in user model by 1

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
like image 923
Mark Shakespeare Avatar asked Jun 19 '26 18:06

Mark Shakespeare


2 Answers

Try this:

@user.increment :books_on_loan, 1
like image 152
pangpang Avatar answered Jun 21 '26 08:06

pangpang


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
like image 34
Rokibul Hasan Avatar answered Jun 21 '26 09:06

Rokibul Hasan