Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Check box on MySql stored as a null or zero

On my rails app I have a list of items (like a task list) and for each item there is a couple of check box to set parameters.

When I submit the form, the checked box are stored as zero and the unchecked as null on DB.

the question is: Is there a way to configure it? To store the data on a more traditional 0 or 1, because I think that storing null as false and 0 as true is a bit confusing, specially if another app (like a C app) needs to read the data.

like image 483
bcsanches Avatar asked Sep 24 '08 05:09

bcsanches


2 Answers

Let's assume that the attribute you are working with is club_member as in "are you a club_member?".

Note that in Ruby/Rails, the way it is working now, if model.club_member will return false if it is not checked (value is null or in Ruby, nil) and true if it is checked (value is 0).

On the whole, I would strongly recommend that instead of letting other applications (like a C app) directly at your data, you should instead build an API in Ruby/Rails to expose the data from your application to external entities. In this manner, you will better encapsulate your application's internals and you won't have to worry about things like this.


However, all that being said, here is your answer:

Use:

value="1"

...attribute in your checkbox HTML tags, and set the default value of the boolean attribute (in your migration) to 0.

like image 179
Yardboy Avatar answered Oct 21 '22 04:10

Yardboy


There are a number of potential reasons for this:

  • Make sure that the column in the database is of type "boolean" in the migration
  • Place a default on boolean values
  • Use "check_box" on the form, not "check_box_tag"
  • Some versions of Rails had this behaviour on generated scaffolds, I think setting the default fixed this, but I can't quite remember.
like image 44
Dan Harper Avatar answered Oct 21 '22 04:10

Dan Harper