Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2008/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 3 我如何只允许特定年龄的用户加入?_Ruby On Rails 3 - Fatal编程技术网

Ruby on rails 3 我如何只允许特定年龄的用户加入?

Ruby on rails 3 我如何只允许特定年龄的用户加入?,ruby-on-rails-3,Ruby On Rails 3,我正在编写一个应用程序,用户必须至少13岁才能加入。我的设置是和,这是我的用户型号: User.rb attr_accessible :birthday validates_presence_of :birthday validate :is_certain_age private def is_certain_age if self.birthday errors.add(:base, 'You need to be at least 13.')

我正在编写一个应用程序,用户必须至少13岁才能加入。我的设置是和,这是我的
用户
型号:

User.rb

  attr_accessible :birthday

  validates_presence_of :birthday

  validate :is_certain_age

  private

  def is_certain_age
    if self.birthday
      errors.add(:base, 'You need to be at least 13.') if self.birthday > Date.today.year - 13
    end
  end
我曾尝试在浏览器中对此进行测试,但当我提交注册表时,它会发布,并且仍然不会创建用户或不创建用户。我不知道发生了什么,因为unicorn服务器不会像WEBrick那样告诉我参数。这就是我所得到的:

127.0.0.1 - - [22/Jun/2013 11:21:12] "POST /users HTTP/1.1" 200 - 0.3460
我对用户的Rspec测试显示了以下故障:

 User 
   Failure/Error: it { should be_valid }
   NoMethodError:
   undefined method `to_datetime' for 2000:Fixnum
注:使用

我做错了什么

您需要的是:

errors.add(:base, 'You need to be at least 13.') if self.birthday > Date.today - 13.years

您将
DateTime
self.birth
)与
FixNum
2000
,这是
Date.today.year-13
)的结果进行比较,而在我上面的代码中:
Date.today-13.years
,结果也是DateTime。

谢谢,我最终将我的验证改为:
validates\u inclusion\u of:birth,:in=>Date.new(1900)…Time.now.years\u ago(13)。to\u Date,:message=>“抱歉,您必须至少13岁才能加入”
。谢谢你的澄清。
errors.add(:base, 'You need to be at least 13.') if self.birthday > Date.today - 13.years