我正在为Ruby验证而苦苦挣扎:在我的Rails应用程序中确认=>为真。考虑以下代码:
# == Schema Information
#
# Table name: things
#
# id :integer not null, primary key
# pin :integer(8)
# created_at :datetime
# updated_at :datetime
#
class Things < ActiveRecord::Base
#attr_accessor :pin
attr_accessible :pin, :pin_confirmation
validates :pin,
:confirmation => true,
:length => { :within => 7..15 },
:numericality => { :only_integer => true }结束
正如上面的代码所示,我的验证在Rails控制台上工作得很好:
1.9.3-p0 :002 > l2 = Thing.create! :pin => 1234567, :pin_confirmation => 1111111
ActiveRecord::RecordInvalid: Validation failed: Pin doesn't match confirmation
....
1.9.3-p0 :003 > l2 = Thing.create! :pin => 1234567, :pin_confirmation => 1234567
=> #<Thing id: 2, pin: 1234567, created_at: "2012-01-30 22:03:29", updated_at: "2012-01-30 22:03:29"> 但是通过rspec和从rails服务器手动测试都会导致验证失败,称它们在做得很好时不匹配。如果我取消注释:pin的attr_accessor,验证将通过,但:pin当然不会写入数据库。
我完全确定我错过了一些明显和重要的东西-只是撞到了一堵砖墙。
发布于 2012-02-02 05:14:15
就像Frederick上面说的,问题是比较String的实例和Integer的实例。
更有可能的是,您的控制器中包含以下内容:
Thing.new(params[:thing]) # note all these params come in as a string实际情况是,由于#pin是一个整数列,因此您将获得以下行为:
my_thing = Thing.new
my_thing.pin = "123456"
my_thing.pin # Will be the integer 123456, the attribute has been auto-cast for you但由于#pin_confirmed只是一个常规属性,而不是整数列,下面是您将看到的奇怪之处:
my_thing = Thing.new
my_thing.pin_confirmation = "123456"
my_thing.pin_confirmation # Will be the *string* "123456", the attribute has been set as is因此,在这种情况下,无论您有什么值,因为它们是通过"params“散列(始终是一组字符串)传入的,您将最终将字符串值分配给两个属性,但它们将被转换为不同的类型。
有几种方法可以解决这个问题。
首先,您可以在数据库中将#pin_confirmation创建为整数列。
另一种方法是您可以为#pin_confirmation添加以下形式的属性设置器:
def pin_confirmation=(val)
@pin_confirmation = val.to_i
endhttps://stackoverflow.com/questions/9071590
复制相似问题