【问题标题】:How to mark the simple_form checkbox based on a Array object?如何基于 Array 对象标记 simple_form 复选框?
【发布时间】:2016-09-07 01:08:52
【问题描述】:

Rails 视图有两个参数

list_of_attributes = ["a1", "a2", "a3", "a4"]
user_selections = ["a2", "a4"]

我能够使用以下 simple_form 定义显示适当的复选框和任何相关的用户选择

<% list_of_attributes.each do |item| %>
   <label>
     <%= check_box_tag "user_selections[]", item, user_selections.include?(item) %>
     <%= item %>
   </label>
<% end %>

如何使用 simple_form f.input 语法定义上述行为?通过以下定义,我可以显示适当的复选框,但任何用户选择都不会被“选中”。

<%= f.input key, as: :check_boxes, collection: list_of_attributes, 
 :label => key, class: "form-control" %>

感谢您的帮助。

【问题讨论】:

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


    【解决方案1】:

    添加选中的属性使 f.input 定义功能。

    <%= f.input key, as: :check_boxes, 
                        collection: list_of_attributes,
                        :label => key, 
                        checked: user_selections,
                        class: "form-control" %>                                    
                  <% end %>
    

    【讨论】:

      【解决方案2】:

      试试这个。这对我使用引导 CSS 很有用。检查我的 github 仓库中的第 25 行 here

      <div class="form-group">
          <div class="row">
              <div class="col-sm-offset-3 col-sm-8">
                  <%= f.collection_check_boxes :your_model_ids, Your_model.all, :id, :list_of_attributes do |cb| %>
                  <% cb.label(class: "checkbox-inline input_checkbox") {cb.check_box(class: "checkbox") + cb.text} %>
              <% end %>
            </div>
          </div>
        </div>
      

      然后在您的 CSS 文件中为上面的自定义 input_checkbox 类使用它

          .input_checkbox input {
          width: auto !important;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-09-22
        • 2020-01-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-18
        • 2011-07-26
        相关资源
        最近更新 更多