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