Validating Rails Virtual Attributes

I this model:

class Bunny < ActiveRecord::Base attr_accessor :number validates_presence_of :number validates_numericality_of :number end 

Whenever I submit a form to create this model, I get the following error:

undefined method `number_before_type_cast 'for # <Bunny: 0x103624338>

+6
ruby validation ruby-on-rails activerecord model
source share
2 answers

I fixed the problem by adding this method to my Bunny model:

 def number_before_type_cast number end 

I don't like this, but I believe it will work until someone publishes a better solution.

+2
source share

Rails generates FIELDNAME_before_type_cast in the model for each field. It saves the value from the form as a string before converting (distinguishing) in this case to a number (it can be a date, for example). This action occurs before saving, but after verification.

Therefore, when validation is performed before casting is performed, it must use the value "before type" to get the value. Since this is not generated for your attribute, it fails.

+1
source share

All Articles