views:

40

answers:

2

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>

A: 

Rails generates the FIELDNAME_before_type_cast in the model for each field. It stores the value from the form as a String before it's converted (cast) in this case to a number (it might be a date for example). This cast occurs before save, but after validation.

So when validation occurs before that cast is performed it has to use the "before type cast" value to get the value. Since this is not generated for your attribute, it fails.

Matt
I see... well that is a good explanation... is there a good solution?
tybro0103
A: 

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

def number_before_type_cast
    number
end

I don't like it, but I suppose it will work until someone posts a better solution.

tybro0103
Yep, I don't have any better idea.
Matt