我如何才允许具有特定年龄的用户加入?

时间:2013-06-22 15:39:18

标签: ruby-on-rails-3

我正在编写一个用户必须年满13岁才能加入的应用程序。我的设置为DeviseUnicorn server,这是我的User模型:

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

我试图在浏览器中对此进行测试,但是当我提交注册表单时,它会POST并且仍然没有创建用户或者没有创建它。我不知道发生了什么事,因为独角兽服务器不会告诉我像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

注意:使用Shoulda Matchers

User valid user age 
   Failure/Error: it { should ensure_inclusion_of(:birthday).in_range(13..150) }
   Did not expect errors to include "is not included in the list"..... 
   ...when birthday is set to 12, got error: 

我做错了什么?

1 个答案:

答案 0 :(得分:1)

你想要的是:

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

您正在将DateTimeself.birthday)与FixNum2000Date.today.year - 13的结果)进行比较,而在上面的代码中:{ {1}},结果也是DateTime。