Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Select boolean with NULL value

First the environment:

Rails 2.1.0, Ruby 1.8.7, Mysql 5.1.54, Ubuntu 11.04

I have a boolean field in my table which starts as NULL, but I can not find a good way to set it to NULL. (This field is basically a yes / no / unanswered field, which true / false / null seems about right for. The client specifically said he would like it to be able to remain null (unanswered).)

Here is my migration (specific names replaced):

class AddQuestionToClients < ActiveRecord::Migration
    def self.up
        add_column :clients, :question, :boolean
    end
    def self.down
        remove_column :clients, :question
    end
end

My controller uses a basic

@client = Client.find(params[:id])
@client.update_attributes(params[:client])

My view has a select (I think this is causing the problem, was never great with form helper selects):

<%= f.select :question, [["Yes", true], ["No", false]], { :include_blank => true, :selected => @client.question } %>

When selecting yes, true is passed; no, false is passed; blank, "" is passed. But "" seems to automatically convert to false when updating the database.

To get around this, I'm doing this:

params[:client][:question] = (params[:client][:question] == "")? nil : params[:client][:question]

But this can't be the right way to do it. What am I missing?

like image 450
d3vkit Avatar asked Apr 03 '26 00:04

d3vkit


1 Answers

I think that you can do that only in that way server side, because when a data is posted is always not nil. So your solution is correct.

If you want to avoid that ugly code you can do a little trick client side using javascript. In fact if you use a disabled element instead of a blank value that value won't be posted and you get nil on server side.

To do that you can add a submit callback that checks whether the question field is blank and if so disable it before posting data. In that way it will work without any server side code.

To disable an element using jQuery you can see this link. So assuming your form has the #form id you can use this code

$(function() {
  $('#form').submit(function () {
    if ($('question-selector').val() == "") {
      $('question-selector').attr('disabled', true);
    }
  })
});
like image 197
Fabio Avatar answered Apr 08 '26 06:04

Fabio