Reputation: 5802
I have the following code in my application.erb file:
<%= hidden_div_if(@cart.line_items.empty?, :id => "cart") do %>
This works fine unless I load a page that does not receive the @cart.line_items object, when I receive the following error:
undefined method `line_items' for nil:NilClass
How do I rewrite the line from my .erb
file to have it behave the same if @cart.line_items
is empty and if @cart
is nil?
Based on the below answers, I changed my code to use:
<%= hidden_div_if([email protected]? && @cart.line_items.empty?, :id => "cart") do %>
*Updated to match the comment Baldrick added to this question (as it is more concise than my original edit).
Upvotes: 2
Views: 1059
Reputation: 168249
<%= hidden_div_if(@cart.to_a.line_items.empty?, :id => "cart") do %>
Upvotes: 0
Reputation: 47532
Use blank?
method of Object class.
An object is blank if it‘s false, empty, or a whitespace string. For example, "", " ", nil, [], and {} are blank. For example
[].blank? #true
"".blank? #true
" ".blank? #true
false.blank? #true
{}.blank? #true
nil.blank? #true
Upvotes: 1
Reputation: 5773
Use @cart.blank?
to check whether it is nil or empty. The blank?
method is a rails extension.
Upvotes: 2