问题
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>
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/3916849/rails-validating-virtual-attributes