I have a few checkboxes that submit and change an attribute’s value on my profile. The attribute was created as a boolean with :default => true. For every other checkbox I set up like this, the attribute’s value is either true/false. However this one checkbox is either true or nil.
Despite setting things up the same, how is that possible? I need the form to only change the value to either true or false. Not nil. Can anyone help me out?
Here’s the migration that adds the column in my Profiles table:
class AddAccessItemsToProfiles < ActiveRecord::Migration
def self.up
add_column :profiles, :access_items, :boolean, :default => true
end
def self.down
remove_column :profiles, :access_items, :boolean, :default => nil
end
end
(Before I go on, I notice the self.down is :default => nil, but I have that in the other migrations that work. Plus I didn’t think that would cause an issue.)
Here is my Controller action to update the value:
def access_items_settings
if current_user.profile.update_attributes(:access_items => params[:access_items])
redirect_to settings_path
else
redirect_to settings_path, :notice => 'Oops, something went wrong. Please try again.'
end
end
Here is the form I submit:
<%= form_tag(access_items_settings_path, :method => :put) do %>
<p class="setting"><%= check_box_tag(:access_items, 1, @user.profile.access_items ? true : false) %>
This lets your items be accessed.
<br><span class="indentClarify">(Some details.)</span></br></p>
<% end %>
(I removed the extra br, p, span, but that did nothing.)
And finally the jQuery:
$(function(){
$(':checkbox').live('click',function() {
$(this).closest('form').submit();
});
});
This has nothing to do with the database default value.
When a check box is unchecked the browse sends no value at all so
params[:access_items]is null and that is what gets saved in the database (since your column allows nulls). The railscheck_boxhelper (unlikecheck_box_tag) uses a hidden field so that an unchecked box also submits a value. You might want to use the same technique.I don’t know what is different about those other checkboxes so can’t comment on those.