将f.collection_check_boxes的复选框与Simple_Form对齐

时间:2013-01-03 19:45:10

标签: ruby-on-rails checkbox simple-form

我正在使用RoR,我正在使用Simple_Form gem来表示我的表单。我有一个对象关系,用户可以有多个角色,在创建过程中,管理员可以选择要应用于新用户的角色。我希望Roles的左边是复选框,右边是水平排列。

// “盒子”管理员 //

而不是当前的

//

“盒子”

管理

//

我目前显示角色的代码就是这个。

  <div class="control-group">
    <%= f.label 'Roles' %>
    <div class="controls">
      <%= f.collection_check_boxes 
                 :role_ids, Role.all, :id, :name %>
    </div>
  </div>

我最感兴趣的部分是f.collection_check_boxes生成这样的代码。

<span>
  <input blah blah />
  <label class="collection_check_boxes" blah>blah</label>
</span>

这让我很难在那里获得一个css类,因为有三个组件需要触及。我已经尝试将诸如虚拟类之类的东西添加到:html哈希,但是虚拟类甚至没有出现在渲染的html中。

非常感谢任何帮助

编辑:解决方案

感谢Baldrick,我的工作人员看起来像这样。

<%= f.collection_check_boxes :role_ids, Role.all, :id, :name,
      {:item_wrapper_class => 'checkbox_container'} %>

我的CSS如下

.checkbox_container {
  display: inline-block;
  vertical-align: -1px;
  margin: 5px;
 }
.checkbox_container input {
  display: inline;
 }
.checkbox_container .collection_check_boxes{
  display: inline;
  vertical-align: -5px;
 }

4 个答案:

答案 0 :(得分:9)

根据doc of collection_check_boxes,有一个选项item_wrapper_class可以为包含复选框的范围提供css类。像这样使用

<%= f.collection_check_boxes :role_ids, Role.all, :id, :name, :item_wrapper_class => 'checkbox_container' %>

使用CSS样式将复选框和标签保持在同一行:

.checkbox_container input {
  display: inline;
}

答案 1 :(得分:4)

在最新的带有2.3.1.0 bootstrap-saas的SimpleForm的2.1.0分支中,安装了bootstrap选项,collection_check_boxes方法导致了一些应用内联项包装器类没有良好效果的跨度。

我能够使用标准输入集合完美地排列表格:as =&gt; :check_boxes方法。然后内联样式完美地运作:

<%= f.input :roles, :collection => valid_roles, :label_method => :last, :value_method => :first, :as => :check_boxes, :item_wrapper_class => 'inline'  %>

我的角色碰巧是一个带有value,label的简单数组。希望这会有所帮助。

答案 2 :(得分:3)

使用Bootstrap,您可以:

<%= f.collection_check_boxes :role_ids, Role.all, :id, :name, :item_wrapper_class => 'inline' %>

答案 3 :(得分:3)

这是使用'rails collection_check_boxes bootstrap'进行DDG搜索的第一个SO页面,但它不是关于Bootstrap,但是这里是Bootstrap 4的解决方案。

这适用于普通的Rails和Bootstrap 4,不需要宝石。 collection_check_boxes是一种简单的Rails方法。

  .form-group
    =f.label :industry_interest
    %br
    =f.collection_check_boxes :industry_interest, Industry.all, :id, :name do |cb|
      =cb.check_box 
      =cb.label
      %br

  .form-group
    =f.label :industry_interest
    =f.collection_check_boxes :industry_interest, Industry.all, :id, :name do |cb|
      .form-check
        =cb.label class: 'form-check-label' do
          =cb.check_box class: 'form-check-input'
          =cb.text 

他们看起来很相似。

https://v4-alpha.getbootstrap.com/components/forms/#checkboxes-and-radios