验证接受总是失败 [英] Validates acceptance always failing

查看:34
本文介绍了验证接受总是失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看不到我遗漏了什么,但显然有些不对.

I can't see what I'm missing, but something is obviously not right.

在模型中:

validates :terms, :acceptance => true, :on => :update

尝试几个选项:

>> a = Factory(:blog_agreement)
=> #<BlogAgreement id: 54, terms: false, created_at: "2011-01-20 11:33:03", updated_at: "2011-01-20 11:33:03", accept_code: "fa27698206bb15a6fba41857f12841c363c0e291", user_id: 874>

>> a.terms
=> false

>> a.terms = true
=> true
>> a.save
=> false

>> a.terms = "1"
=> "1"
>> a.save
=> false

>> a.terms = 1
=> 1
>> a.save
=> false
>> a.errors.full_messages
=> ["Terms must be accepted"]

推荐答案

更新答案..

所以事实证明问题是将术语作为表中的实际列.一般来说,validates_acceptance_of 是在没有这样的列的情况下使用的,在这种情况下,它定义了一个属性访问器并将其用于验证.

Updated answer..

So it turns out that the problem was having terms as an actual column in the table. In general validates_acceptance_of is used without such a column, in which case it defines an attribute accessor and uses that for its validation.

为了使 validates_acceptance_of 在映射到真实表列时起作用,必须传递 :accept 选项,例如:

In order for validates_acceptance_of to work when it maps to a real table column it is necessary to pass the :accept option, like:

validates :terms, :acceptance => {:accept => true}

这样做的原因与 Active Record 中的类型转换有关.当命名属性实际存在时,AR 会根据数据库列类型进行类型转换.在大多数情况下,接受列将定义为布尔值,因此 model_object.terms 将返回 true 或 false.

The reason for this has to do with typecasting in Active Record. When the named attribute actually exists, AR performs typecasting based on the database column type. In most cases the acceptance column will be defined as a boolean and so model_object.terms will return true or false.

当没有这样的列时,attr_accessor :terms 简单地返回从 params 散列传递给模型对象的值,该值通常是来自复选框的 1"领域.

When there's no such column attr_accessor :terms simply returns the value passed in to the model object from the params hash which will normally be "1" from a checkbox field.

这篇关于验证接受总是失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆