Rails validating virtual attributes

纵然是瞬间 提交于 2019-12-22 05:23:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!