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?

4

1 回答 1

0

有两种方法可以做到这一点。假设您的模型设置如下:

class Product < ActiveRecord::Base
  ...
  validates_uniqueness_of :quantity, scope: :name
  ...
 end
  1. 使用本地化文件。这是执行此操作的首选方式。在您的 config/locales/en.yml(或您所在的任何语言环境)中,执行以下操作:

    product:
      attributes:
        quantity:
          taken: "Product and quantity are not unique. And, Oreo's are delicious."
    
  2. 不太喜欢的方式,但仍然应该直接在验证本身中工作。

    validates_uniqueness_of :quantity, scope: :name, message: "Product and quantity are not unique. And, Oreo's are delicious."
    
于 2013-10-27T01:32:36.200 回答