Rails validation on one to many associations

Viewed 20

I am new to Rails. I have 2 models - User and Order. A user can have multiple orders with the same order number but another user cannot have that order number. How can I implement this validation to make sure that order number is unique across users? Thanks in advance.

1 Answers

You can use a base error like this: (if it is on your order model)

errors.add :base, :number_already_used, if: Order.where(number: self.number).where.not(user_id: user_id).exists?
Related