Search code examples
mysqlruby-on-railscomparisonbooleantinyint

Correct way to check against boolean values in Rails


I'm facing issues when I'm trying to check for boolean values in Rails. Earlier my condition used to check against a boolean value against 1 or 0 and this worked. But recently, this doesn't work any more.

When I check them at MySQL level, the booleans are stored as tinyint(1) with values 1 and 0. But when I print those values in the rails development.log, they come up as true and false respectively.

Earlier comparison logic
is_admin == 1

When I check for true and false now instead of 1 and 0(because of the recent issue) things work well. I'm not sure why this didn't fail for me earlier.

Current comparison logic
is_admin == true

I'm also not 100% confident that a comparison of a boolean column should be done against true or false always in the context of Rails or it should be against 1 and 0.

One thing I did realize in the process is, the earlier comparison was between say 1 (an integer) and true (the actual boolean) is evaluating to false. This I can now understand, but I'm still not able to get over how did this logic seem to work for me earlier.

I'd be interested to hear the best practice to do these kind of checks in Rails.


Solution

  • Different databases store booleans in different ways. Mysql stores them as 0 or 1. These are translated into false and true by rails. Generally you you treat them as booleans in your ruby code.

    This code

    if is_admin == true
    

    is redundant. you might as well just say

    if is_admin
    

    since the result will be the same either way.