06 Mar 2013, 15:46
Distorted_pragsmall

Enrique Sánchez (17 posts)

Why is ”:length” written with a colon before it and a => after, but “uniqueness” isn’t?

validates :title, uniqueness: true, :length => { :minimum => 10, :message => :too_short}
06 Mar 2013, 16:42
Samr_small_pragsmall

Sam Ruby (549 posts)

You are welcome to write that same line as follows:

validates :title, uniqueness: true, length: { minimum: 10, message: :too_short}

Note: message is typically a ‘string’ not a :symbol.

06 Mar 2013, 16:50
Distorted_pragsmall

Enrique Sánchez (17 posts)

Ah, this makes so much more sense to my brain. Thank you.

07 Apr 2013, 10:33
Generic-user-small

Louis Rhys (22 posts)

How do I add a custom message for the “uniqueness: true” part?

07 Apr 2013, 14:35
Samr_small_pragsmall

Sam Ruby (549 posts)

app/views/products/_form.html.erb has full control over what is put in the HTML output.

Section 15.3 shows you how to override the value provided to you in full_message. You can provide an error.messages.taken string in the en translation.

For truly custom processing, you can write your own before_action callback (see chapter 20), and section 9.2 show you how to add custom messages.

07 Apr 2013, 12:05
Generic-user-small

Louis Rhys (22 posts)

I see. What I meant was, consider these two lines:

validates :price, numericality: {greater_than_or_equal_to: 0.01}

and

validates :title, uniqueness: true

In the first one, since the numericality part takes a hash as its value, I can seem to add a custom message, like

validates :price, numericality: { greater_than_or_equal_to: 0.01, message: 'must be at least one cent' }

However, in the second code uniqueness takes only “true” instead of a hash, so is there a way to put the custom message in code?

07 Apr 2013, 14:38
Samr_small_pragsmall

Sam Ruby (549 posts)

It doesn’t look like it—at the current time.

If this is something that interests you, consider looking into how to contribute to Rails. Lots of people do it. You can too!

27 Apr 2013, 05:34
Generic-user-small

Patrik Nygren (1 post)

Just wanted to add a few lines about the topic for people who run in to same problems as me which was with the regexp on the validation part. My validation with

 validates :image_url, allow_blank: true, format: {
    with:    %r{\.(gif|jpg|png)\$}i,
    message: 'must be a URL for GIF, JPG or PNG image.'
  }
 

had to be changed to
 
validates :image_url, allow_blank: true, format: {
    with:    %r{\.(gif|jpg|png)\Z}i,                         # heres the change
    message: 'must be a URL for GIF, JPG or PNG image.'
  }
 

for the functional test to work..
  You must be logged in to comment