Ruby on rails 比较日期:;将日期与“无”进行比较失败“;

Ruby on rails 比较日期:;将日期与“无”进行比较失败“;,ruby-on-rails,validation,date,Ruby On Rails,Validation,Date,我有一个客户模型,它有许多项目。在项目模型中,我想验证项目开始日期是否总是在项目结束日期之前或同一天。这是我的项目模型: class Project < ActiveRecord::Base attr_accessible :end_on, :start_on, :title validates_presence_of :client_id, :end_on, :start_on, :title validate :start_has_to_be_before_end

我有一个客户模型,它有许多项目。在项目模型中,我想验证项目开始日期是否总是在项目结束日期之前或同一天。这是我的项目模型:

class Project < ActiveRecord::Base
  attr_accessible :end_on, :start_on, :title

  validates_presence_of :client_id, :end_on, :start_on, :title
  validate :start_has_to_be_before_end

  belongs_to :clients

  def start_has_to_be_before_end
    if start_on > end_on
        errors[:start_on] << " must not be after end date."
        errors[:end_on] << " must not be before start date."
    end
  end
end
奇怪的是,运行这个测试给了我三个错误,都是指我的验证方法中的这一行
if start\u on>end\u on
,对nil:NilClass说
undefined method'>',两次和一次
比较日期与nil失败


如何使测试通过?

您正在创建一个项目,该项目的字符串值为:start\u on和:end\u on。那不太可能奏效。Rails可能会尝试更智能地解析这些,我不确定。。我不会指望的。很有可能正在进行一些强制操作,并且值被设置为零

我会这样做:

project = Project.new(client_id: 1, 
                      start_on: 2.days.from_now.to_date, 
                      end_on: Time.now.to_date, 
                      title: "Project title")

修复-没有
nil>x
。它不起作用。@pst但为什么start_为零?所以,现在我们有进展了!它在哪里设置为
start\u on
(指定为命名参数)将更新
start\u on
访问器?如果设置为字符串而不是实时对象,会发生什么?如果它是在构造函数之后设置的呢?也就是说,沿着轨迹走。报告的绒毛不是您要找的绒毛。太好了,这修复了测试,谢谢!另外,我将我的项目模型改为使用,因此现在代码更干净了:
验证:end_on,date:{after_or_equal_to::start_on}
验证:start_on,date:{before_or_equal_to::end_on}
project = Project.new(client_id: 1, 
                      start_on: 2.days.from_now.to_date, 
                      end_on: Time.now.to_date, 
                      title: "Project title")