views:

1521

answers:

4

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.

+2  A: 

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.
Dan Harper - Leopard CRM
The column on db is set to true and I forced its default value to false. The null is gone, but now all values are zero! I am creating the check box on the fly using dynamic dom, maybe this is the issue.
bcsanches
Using it dynamically might still be OK. I'd recommend doing it via standard Rails helpers first, then mimic the generated HTML in your DOM manipulation.
Dan Harper - Leopard CRM
+2  A: 

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.

Yardboy
Thank you! This resolved the issue (including the value=1) and setting default value on the migration to 0.
bcsanches
A: 

What about:

value.to_i.zero?

>> a=nil
=> nil
>> a.to_i.zero?
=> true
>> a=0
=> 0
>> a.to_i.zero?
=> true
>> a=3
=> 3
>> a.to_i.zero?
=> false
Fabian
A: 

From the rails documentation:

An object is blank if it’s false, empty, or a whitespace string. For example, “”, “ “, nil, [], and {} are blank.

This simplifies: if !address.nil? && !address.empty?

…to: if !address.blank?

robodo