Friday, February 24, 2012

Validating Virtual Attributes in Rails 3.1

When validating virtual attributes in Rails it's important to remember that they are just that - virtual attributes. I spent almost an hour last night trying to figure out why my validations were throwing an error when I called Object.valid? My class was structured similar to the following (forgive me, I am a Rails n00b):
Class User

attr_accessor :password

validates :password,
:presence => true,
:on => create

validates :password,
:length => { :minimum => 6 :maximum => 8 },
:if => :password?
.
.
.
end
When calling valid? on the User object I got a method undefined error for password?. I could't quite figure it out and I was wondering what I was doing wrong until eventually I tried appending the following to the bottom of the class definition:
.
.
.
def password?
 self.password.present?
end
.
.
.
An seemingly simple and obvious solution, I know, but this took me about an hour to figure out after Stack Overflow failed me for the first time.

I hope this helps save someone else the frustration I endured.

No comments: