Follow Along as I Stumble on the Path to Learning RoR

Posts tagged “conditional

Rails Queries not Finding Nil Values

I had some queries that were not working and I couldn’t figure out how to make them work.  Basically, I was looking for fields with nil values, so I tried:

Model.where(‘variable = ?’, nil)….and didn’t get any results

So just for the heck of it, I tried:

Model.where(‘variable != ?’, nil)…but still no results.  How is that possible?  It either has to be a value or it isn’t right?

Well, apparently you can’t use normal comparison operands with nil/null.  However, instead of =, you can compare for nil using <=>

So I ended up doing:

Model.where(‘variable <=> ?’, nil)

and it worked, finding the nil values.


How to Check the Controller

I needed to write a conditional statement checking the controller, I figured out the syntax through this post:

http://stackoverflow.com/questions/5222723/how-do-i-write-a-conditional-to-test-which-page-im-on-in-rails