Reputation: 37
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 ?
Upvotes: 0
Views: 2386
Reputation: 11235
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
.
Upvotes: 3
Reputation: 4561
Just add a check that the record isn't nil in your if statement as shown:
@b = Book.find(params[:book][:id])
if [email protected]_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!
Upvotes: 0