[英]rails : undefined method `>' for nil:NilClass
I'm a beginner in rails and I need to compare 2 DateTime on my controller : 我是Rails的初学者,我需要在控制器上比较2 DateTime:
@b = Book.find(params[:book][:id])
if @b.expiry_date > DateTime.now
... something here ...
end
But I get this error : 但是我得到这个错误:
undefined method `>' for nil:NilClass
Anyone have an idea why ? 有人知道为什么吗?
Operators are methods in ruby, so your undefined method '>' for nil:NilClass
error indicates that @b.expiry_date
is nil on this line: if @b.expiry_date > DateTime.now
. 运算符是ruby中的方法,因此您
undefined method '>' for nil:NilClass
错误,表明此行上@b.expiry_date
为nil: if @b.expiry_date > DateTime.now
。
You can use a short-circuiting logic to only evaluate the condition if @b.expiry_date
is present. 如果存在
@b.expiry_date
则可以使用短路逻辑来评估条件。
if @b.expiry_date && (@b.expiry_date > DateTime.now)
The if expressions is only true if both sides of the &&
are also true, so (@b.expiry_date > DateTime.now)
won't be executed if the first condition, @b.expiry_date
, is false or nil. if表达式仅在
&&
两面也都为true时才为true,因此如果第一个条件@b.expiry_date
为false或nil,则(@b.expiry_date > DateTime.now)
将不会执行。
Otherwise, you'll need to add logic/validations to ensure the existence of expiry_date
. 否则,您将需要添加逻辑/验证以确保存在
expiry_date
。
Just add a check that the record isn't nil in your if statement as shown: 只需在if语句中添加一条检查记录是否为nil的检查,如下所示:
@b = Book.find(params[:book][:id])
if !@b.expiry_date.nil? && @b.expiry_date > DateTime.now
... something here ...
end
If all Books are supposed to have expiry dates you should add a validation that insists an expiry date is included when creating/updating a Book record in your Book Model! 如果所有书籍都应具有有效期限,则应添加一个验证,要求在您的书籍模型中创建/更新书籍记录时,必须包括有效期限!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.