0

So I have a table with books and a table with borrowers. A User borrows a book of choice, and later it is shown on the page who borrowed it and what was borrowed.

Now I also have a column in my books table which is count, to see how many times the book has been borrowed.

Should the code for it go into borrowing controller? I tried to put it under def create action before.

Did something like count = Book.find(params[:id]), count = params[:count] + 1

But this solution seemed to not work, it did't even find the book that I was talking about.

Kaspar
  • 1,532
  • 3
  • 21
  • 41

2 Answers2

0

if your borrowers table has association with books table. than you can add a callback in model after_create :increase_count_id and create a method in borrower model

def increase_count_id
 self.book.update_column(count: self.book.count + 1)
end
Nitin Jain
  • 3,013
  • 2
  • 21
  • 35
  • Does not seem to make a +1 still but creates a error when I make a new book: undefined local variable or method `increase_count_id – Kaspar Jan 18 '14 at 15:18
  • I have made the associations in models that books has burrows and burrows belongs to book – Kaspar Jan 18 '14 at 15:18
  • Okay now I get it when borrowing a new book: undefined local variable or method `increase_count_id' . But I have the callback written in the borrower model and the action in borrower controller. – Kaspar Jan 18 '14 at 15:23
  • It's like it does not see that I have it defined in my controller. It is written corrently too, cannot be typo. – Kaspar Jan 18 '14 at 15:23
  • the method should also gone too borrower model :) – Nitin Jain Jan 18 '14 at 15:24
  • Silly me... But now it gives a wrong number of arguments error : wrong number of arguments (1 for 2) But it has everything needed? – Kaspar Jan 18 '14 at 15:26
  • Nevermind I changed it to :count, self.book and now it works! Thanks alot – Kaspar Jan 18 '14 at 15:28
  • okay change the method code to `book = self.book ` , `book.count = book.count +1` , `book.save` – Nitin Jain Jan 18 '14 at 15:28
0

You can also use this:

book.increment!(:count, 1)
Ahmad Hussain
  • 2,234
  • 17
  • 24
  • But why the exclamation mark in the end? I don't understand. Other than that, it is even a nicer solution to my problem! – Kaspar Jan 20 '14 at 00:32
  • ! means update changes in calling object. You can check example over here: http://stackoverflow.com/questions/612189/why-are-exclamation-marks-used-in-ruby-methods?answertab=votes#tab-top – Ahmad Hussain Jan 20 '14 at 05:13