0

I've set up a validation rule on my Product model to check that two fields, name and quantity, are unique. For example, you can have

  • Oreos 12-pack
  • Oreos 100-pack

And both are valid entries. However, you can't have two Oreos 100-pack records.

I have used the approach described in this question to set up the rule (Validate uniqueness of multiple columns), however the default error message simply highlights the first field and says it's already taken, which does not accurately describe the problem to a user trying to insert product information.

If this is the general Rails solution to validating uniqueness on multiple fields, how can I set up the validation message appropriately depending on which rule has failed.

If there are other solutions that will automatically display an appropriate error message, what would it be?

Community
  • 1
  • 1
MxLDevs
  • 19,048
  • 36
  • 123
  • 194

1 Answers1

0

There are two ways to do this. Assuming that your model is setup like this:

class Product < ActiveRecord::Base
  ...
  validates_uniqueness_of :quantity, scope: :name
  ...
 end
  1. Use localization files. This is the preferred way to do it. In your config/locales/en.yml (or whichever locale you're in), do the following:

    product:
      attributes:
        quantity:
          taken: "Product and quantity are not unique. And, Oreo's are delicious."
    
  2. Less preferred way, but should still work is directly in the validation itself.

    validates_uniqueness_of :quantity, scope: :name, message: "Product and quantity are not unique. And, Oreo's are delicious."
    
d_ethier
  • 3,873
  • 24
  • 31