danh
danh

Reputation: 62676

Rails 3 validate presence of many columns with custom messages

Is there a way to specify many validations like this more concisely?

validates :col_a, :presence => {:message => 'col_a cannot be blank'}
validates :col_b, :presence => {:message => 'col_b cannot be blank'}
validates :col_c, :presence => {:message => 'col_c cannot be blank'}

I'd settle for a generic message if I had to.

Upvotes: 10

Views: 8019

Answers (3)

Harish Shetty
Harish Shetty

Reputation: 64363

You can give multiple field names to a validator

validates :col_a, :col_b, :col_c, :presence => true

You can specify multiple validators in the same line.

validates :col_a, :col_b, :col_c, :presence => true, :numericality => true

The full error message will contain the field name. You don't need to add the field name prefix. If you want to use a custom message then:

validates :col_a, :col_b, :col_c, :presence => {:message => "empty value found"}

Upvotes: 27

Supportie
Supportie

Reputation: 181

You can use

validates :col_a, presence: true
validates :col_b, presence: true
validates :col_c, presence: true

Upvotes: 2

jbearden
jbearden

Reputation: 1869

Use the validates_presence_of helper.

validates_presence_of :col_a

EDIT

You could clean it up a bit with validates_each. There is an example on the api page. http://api.rubyonrails.org/classes/ActiveModel/Validations.html

Hope that helps

Upvotes: 1

Related Questions