2009-02-25 77 views

回答

39

如果您在表单的上下文中使用check_box,那么该复选框将显示该字段具有的任何值。

@user = Person.find(:first) 
@user.active = true 
check_box 'user', 'active' #=> will be checked by default 

如果您使用,第三个参数是初始状态(check_box_tag doc):

check_box_tag "active", 1, true 
+0

我不读/写check_box值的分贝,所以切换到check_box_tag和使用真正的开关解决了这个问题。谢谢! – daustin777 2009-02-25 17:52:25

+0

_tag方法适用于非模型表单。非_tag的是。 – wesgarrison 2009-02-26 16:51:59

+0

@wesgarrison我正在使用一个像这样的check_box_tag <%= check_box_tag“benificiary_id [#{b.id}]”,b.id,:name =>“benificiary_id []”%>我该如何检查是否有任何记录在更新过程中是否检查过?默认情况下,我的更新操作取得所有复选框值,即使其中一些未选中:( – 2011-11-06 08:35:19

6

在你的控制器的新动作,尝试:

@user = User.new(:male => true) 

其中:男性是您希望在/users/new页面上默认检查的属性。这会将:male属性传递给值为true的视图,从而生成一个复选框。

0

这适用于Rails 2.3.x和Rails 3.0.x!

在控制器中的新动作中,该复选框设置为true。

# in the controller 
def new 
    @user = Person.find(:first) 
    @user.active = true 
end 

形式:该复选框在创建检查(通过调用新的),但如果验证失败复选框保持设置有用户有职位的价值。

# in the view 
<%= form_for ..... |f| %> 
    ... 
    <%= f.check_box :active %> 
    ... 
<% end %> 

的其他方式,但不是那么好(如果你想改变的逻辑,你必须做出新的迁移)是设置:默认=> 1在给定的模型的迁移和属性。

class CreatePeople < ActiveRecord::Migration 
    def self.up 
    create_table :people do |t| 
     ... 
     t.boolean :active,    :null => false, 
             :default => 1 
     t.timestamps 
    end 
    end 

    def self.down 
    drop_table :people 
    end 
end 
36

的Rails 3.x的

= form_for(@user) do |f| 
    = f.check_box :subscribe, {checked: true, ...} 

此设置的选中状态,以真实,应该正常工作。注意ruby 1.9.x的散列语法,对于ruby 1.8.x使用散列标签格式{:checked => true,...}

0

我是这样做的。

值为0隐藏字段上方check_box_tag

<%= hidden_field_tag :subscribe, '0' %> 
<%= check_box_tag :subscribe, '1', params[:subscribe] != '0' %> 

在服务器检查与!= '0'

subscribe = params[:subscribe] != '0' 
3

我感到非常震惊,没有一个答案解决问题的100%。
由于所有建议的解决方案都会在编辑表单上显示checked结果,即使用户未选中复选框。

<%= f.check_box :subscribe, checked: @event.new_record? || f.object.subscribe? %>

Works的导轨4 +,不低于测试。

1

简单

<%= f.check_box :subscribe, checked: "checked" %>