How to use validates?

I can't get this to work.

class User < ActiveRecord::Base

validates :firstname, :presence => true, :message => "First name is missing"

end

And no error message. Why?

I can't get this to work.

class User < ActiveRecord::Base

validates :firstname, :presence => true, :message => "First name is missing"

end

And no error message. Why?

What do your views look like, either at the layout level or the users/new>edit level? If you don't put some sort of view code in place, you won't ever see the errors if they're being set. Are you able to see other errors, and just not that one?

Walter

It's more of a basic question. How do I get that single error, in the simples way? @model.errors..something

Did you mean: validates :firstname, :presence => {:message => "First name is missing"} ?

PS: have you defined to show error_messages in your view?

or use the plugin dynamic_form and the old <%= f.error_messages %>-Helper in your form

Bente Pieck wrote in post #978180:

I think, I still missunderstand you. But perhaps this is, what you need:

You want to iterate through errors:

@user.errors.each do |attr, message|
  do something with attr and message
end

If you want an array of all full_messages, use:
@user.errors.full_messages
(how they are handling it in this episode: [http://railscasts.com/episodes/211-validations-in-rails-3](http://railscasts.com/episodes/211-validations-in-rails-3))

@user.errors.generate_message(:firstname)

Or if you need the other methods of @user.errors, look here:
[http://api.rubyonrails.org/](http://api.rubyonrails.org/)
ActiveModel::Errors

Is this what you need?

PS:
validates :firstname, :presence => true, :message => "First name is missing"
75 validations = defaults.slice!(:if, :unless, :on, :allow_blank, :allow_nil
)
only these 5 options are possible global-options. :message is not one of them. So I am sure, your way won't do what you want it to do.

I think this is confused mix of old

validates_presence_of :firstname, :message => message

and newer sexy validations

validates :attribute, :presence => options_hash/true/array/

if you look in the source:

Bente Pieck wrote in post #978687:

Is this what you need?

-- best regards Bente Pieck

Yes! I've used some of this without luck but I probably did something wrong. With your help, your code, I'm sure I'll get it right. Thank you very much. :slight_smile: