为什么复选框默认=> true会变为nil作为其他选项而不是false吗?

时间:2012-01-21 02:34:30

标签: ruby-on-rails-3 checkbox boolean

我有一些复选框可以提交和更改我的个人资料中的属性值。该属性创建为带:default => true的布尔值。对于我设置的每个其他复选框,属性的值为true / false。但是,此复选框可以是truenil

尽管设置相同,但这怎么可能?我需要表单只将值更改为true或false。不是。任何人都可以帮助我吗?

以下是在我的“个人资料”表中添加列的迁移:

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

(在我继续之前,我注意到self.down是:default => nil,但我在其他有效的迁移中也有这个。加上我认为这不会导致问题。)

以下是我更新值的Controller操作:

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

以下是我提交的表格:

<%= form_tag(access_items_settings_path, :method => :put) do %>
  <p class="setting"><%= check_box_tag(:access_items, 1, @user.profile.access_items ? true : false) %>
  &nbsp;This lets your items be accessed.
  <br><span class="indentClarify">(Some details.)</span></br></p>
<% end %>

(我删除了额外的brpspan,但这没有做任何事情。)

最后是jQuery:

$(function(){
    $(':checkbox').live('click',function() {
        $(this).closest('form').submit();
    });
});

1 个答案:

答案 0 :(得分:1)

这与数据库默认值无关。

如果取消选中复选框,则浏览器根本不发送任何值,因此params[:access_items]为空,这是保存在数据库中的内容(因为您的列允许空值)。 rails check_box helper(与check_box_tag不同)使用隐藏字段,以便未选中的框也提交值。您可能想要使用相同的技术。

我不知道其他复选框有什么不同,所以不能评论那些。