Comparing strings to potentially null values in Rails

I’m fairly new to Rails, and Ruby, for that matter, and not yet sure of some basic things. I’ve read a bunch about how to test for (and not test for) nil or empty, and also about how to avoid that need – for instance, see this very useful post on keenertech.com.

But, I can’t seem to find anyone addressing my particular issue, which is that I need to compare a db value – say, user.middle_name – with a string imported from a CSV file (using Roo); I want to know if the imported data differs from the db value, but if user.middle_name is null, and I try user.middle_name == file_row[“middle_name”], I get a value of false, because, of course, nil does not equal an empty string (and all fields are imported from the CSV as strings, not nils).

In the world of SQL, I might say something like isnull(user.middle_name, ”) = file_row.middle_name, but I don’t see anything like that in Ruby.  I could also try user.middle_name.to_s == file_row[“middle_name”], which should be fine here, but if the field is a date, or number, or boolean, it may not match.

So, my solution was as follows:

(user.middle_name || "") == file_row["middle_name"]

This seems to work just fine, but I just wonder, is it the “right” way to do this? Am I missing something? If anyone cares to share some insight, or if this is right and someone finds it helpful … well, that’s what this post is for.

 

No Comments

Leave a Reply

Your email is never shared.Required fields are marked *