I'm a beginner in rails and I need to compare 2 DateTime on my controller :
@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
.
You can use a short-circuiting logic to only evaluate the condition if @b.expiry_date
is present.
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.
Otherwise, you'll need to add logic/validations to ensure the existence of expiry_date
.
Just add a check that the record isn't nil in your if statement as shown:
@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!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.