简体   繁体   English

Rails验证虚拟属性

[英]Rails validating 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> 未定义的方法`number_before_type_cast'用于#<Bunny:0x103624338>

I fixed the problem by adding this method to my Bunny model: 我通过将此方法添加到我的Bunny模型来修复问题:

def number_before_type_cast
    number
end

I don't like it, but I suppose it will work until someone posts a better solution. 我不喜欢它,但我认为它会起作用,直到有人发布更好的解决方案。

Rails generates the FIELDNAME_before_type_cast in the model for each field. Rails在模型中为每个字段生成FIELDNAME_before_type_cast 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). 它将表单中的值存储为String,然后在此情况下将其转换(转换)为数字(例如,可能是日期)。 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. 因此,在执行强制转换之前进行验证时,必须使用“before type cast”值来获取值。 Since this is not generated for your attribute, it fails. 由于这不是为您的属性生成的,因此会失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM