I would like to display a line of text only if an object called @foo is set. In my view, I'm trying something like this:
<% if [email protected]_record? || [email protected]? %>
Foo is not a new record or nil
<% end %>
But this fails, returning You have a nil object when you didn't expect it!
I'm pretty sure this happens because of the new_record?
method.
How do I check if something is not a new record or nil without causing an error?
In PHP, it would be achieved by asking if(!empty($foo))
but even the empty?
method in rails causes the same error to be returned.
Any ideas?
Ruby is an open-sourced object-oriented programming language developed by Yukihiro Matsumoto. In Ruby, everything is treated as an object. true, false and nil are built-in data types of Ruby. Note: Always remember in Ruby true, false, and nil are objects, not numbers.
That means that an empty string is NOT nil and an empty array is NOT nil. Neither is something that is false nil. => NilClass nil.nil? => true "".nil? => false false.nil? => false [].nil? For more info on .nil and NilClass, check out this sweet Ruby Guides article! .empty? [RUBY] .empty means that the length object you are trying to evaluate == 0.
Calling methods on a null object causes the NullPointerException to be thrown. In C, operating on invalid pointer may lead to unexpected results. As you may expect, there should be a Ruby way to check if object is nil. Here it is: # Ruby code # if my_object. nil ? puts "There is no object!"
In Ruby, everything is treated as an object. true, false and nil are built-in data types of Ruby. Note: Always remember in Ruby true, false, and nil are objects, not numbers. Whenever Ruby requires a Boolean value, then nil behaves like false and values other than nil or false behave like true.
How about:
<% if [email protected]? && [email protected]_record? %>
Hello!
<% end %>
First off, you need to be using AND logic rather than OR logic here, since any ActiveRecord object meets at least one the requirements of "not nil" or "not a new record".
Second, checking for nil first ensures that the second check isn't run if the first one fails. The error is thrown because you can't use #new_record?
on an object that doesn't support it, so checking for nil first ensures that that method is never run on a nil.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With