0

I have three models : User, Product and Loan. A loan has a borrowing_date, a returning_date and a current boolean.

  • I want to prevent a user to ask borrowing a product more than once.
  • I want to prevent my loan model to have more than one current loan.

How can I do that ?

Here are my trials, but it didn't came out right :

def only_one_current_loan
  errors.add(:current, I18n.t('validation.loan.only_one_current')) unless Loan.find_by(product: self.product, current: true).count < 1
end

def only_one_request_at_a_time
  errors.add(:product_id, I18n.t('validation.loan.only_one_request_at_a_time')) unless Loan.where(product_id: self.product.id, user_id: self.user.id, borrowing_date: nil).count < 1
end
Flo Rahl
  • 1,044
  • 1
  • 16
  • 33
  • Are you calling from a callback instead of validation? – Nerve Jul 08 '13 at 07:38
  • I'm using `validate only_one_current_loan` and `validate only_one_request_at_a_time`. – Flo Rahl Jul 08 '13 at 07:41
  • I guess you'll need to symbolize them. `validate :only_one_current_loan` – Nerve Jul 08 '13 at 08:18
  • It's a typing mistake in my comment. I really wrote `validate :only_one_current_loan` in my model... – Flo Rahl Jul 08 '13 at 08:22
  • `.nil? < 1` This seems fishy. nil? will return true or false. which doesn't respond to <. It is best to debug things in such cases. Add a debugger there and check the `unless` conditions. – Nerve Jul 08 '13 at 08:29
  • Oops, I wrote that question way too fast. It's not `.nil?` but `.count`... Sorry for the inconvenience... – Flo Rahl Jul 08 '13 at 08:37

0 Answers0