Virtual Attribute Model Validation

I have an Order model with two virtual attributes for account number
and sort code for setting up a recurring bank payment (Direct Debit in
the UK). I do not want to save the account details in my database
(similar to the reason for credit card numbers) but obviously collect
the details through a form.

I have tried this:

validates_numericality_of :dd_account, :only_integer => true
validates_length_of :dd_account, :is => 8, :wrong_length =>
“^Account number|Must be 8 digits long”

but I get the following exception:

/Users/owain/.gem/ruby/1.8/gems/activerecord-2.3.4/lib/active_record/
attribute_methods.rb:255:in method_missing' /Users/owain/.gem/ruby/1.8/gems/activerecord-2.3.4/lib/active_record/ validations.rb:1019:insend’
/Users/owain/.gem/ruby/1.8/gems/activerecord-2.3.4/lib/active_record/
validations.rb:1019:in `validates_numericality_of_without_reflection’

which I suspect is that this type of validation will not work with
virtual attributes. Is this the case???

Is the approach below the best solution or even work?

validate :custom_validation

def custom_validation
errors.add(:dd_account, “Some error message”) if detect_something
end

Additionally, can you use the class methods in custom methods? I
would like to use validates_length_of etc if I go down the custom
method route. Again, if I do manage to use them will they work on
virtual attributes?

Thanks,

O.

def custom_validation
errors.add(:dd_account, “Some error message”) if detect_something
end

You can do this part. How about using the class methods so I can
avoid resorting to this?

def dd_details
errors.add(:dd_account, “^Account number|Must be 8 digits long”)
unless dd_account.to_s.length == 8
end

Ok, that’s an easy one but some of the others are a little more tricky
and I would like to use them.

On Nov 12, 12:36 pm, icke [email protected] wrote:

/Users/owain/.gem/ruby/1.8/gems/activerecord-2.3.4/lib/active_record/
attribute_methods.rb:255:in method_missing' /Users/owain/.gem/ruby/1.8/gems/activerecord-2.3.4/lib/active_record/ validations.rb:1019:in send’
/Users/owain/.gem/ruby/1.8/gems/activerecord-2.3.4/lib/active_record/
validations.rb:1019:in `validates_numericality_of_without_reflection’

which I suspect is that this type of validation will not work with
virtual attributes. Is this the case???

That error is getting raised because the validation is trying to call
attribute_name_before_type_cast
If you implement that method it might just work.

Fred