Lee
Lee

Reputation: 487

Rails Validations and custom error messages

I'm having an issue with Validations, if I use the following syntax all is well (no failures).

validates :title, uniqueness: true

However if I change it to this, I get a failure.

validates :title, uniqueness: {message: 'Title must be unique'}

Here is the test for completeness:

test "product is not valid without a unique title " do
  product = Product.new( title: products(:ruby).title,
  description: "yyy",
  price: 1,
  image_url: "fred.gif" )

  assert !product.save
  assert_equal "has already been taken", product.errors['title'].join('; ')
end

I have a fixture that adds the book title for the Ruby product etc.

As I understand it the two validations should be the same, just that one gives a custom error message. This is the error I get when using the custom message.

1) Failure: test_product_is_not_valid_without_a_unique_title_(ProductTest) <"has already been taken"> expected but was <"Title must be unique">.

Thanks in advance for your help.

Upvotes: 1

Views: 2045

Answers (1)

jdoe
jdoe

Reputation: 15771

Here:

assert_equal "has already been taken", product.errors['title'].join('; ')

you expect to see "has already been taken" in the errors hash, but you've overridden this message with your custom message. Test shows that your custom message appears as it should. Why do you still expect the default message? You have to expect Title must be unique.

TIP Don't supply the name of your field in your custom message. Rails will handle it automatically when generating errors by, say, product.errors.full_messages ("must be unique" would be enough).

Upvotes: 1

Related Questions