在 Rails 表单 erb 中使用 Bootstrap 格式化复选框?



我在 Rails 视图表单中使用了多个复选框。我正在使用 Bootstrap 4 进行样式设置。如果复选框有引导样式,例如:

<div class="input-group mb-3">
<div class="input-group-prepend">
<div class="input-group-text">
<input type="checkbox" aria-label="Checkbox for following text input">
</div>
</div>
<input type="text" class="form-control" aria-label="Text input with checkbox">
</div>
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<input type="radio" aria-label="Radio button for following text input">
</div>
</div>
<input type="text" class="form-control" aria-label="Text input with radio button">
</div>

如何在 ERB 对象中实现多个类样式?这是我尝试实现的代码:

<%= f.collection_check_boxes(:authorization_ids, Authorization.all, :id, :auth_name, { checked: @account.try { |a| a.authorization_ids.map(&:to_param) } }, multiple: true, # WOULD LIKE TO IMPLEMENT BOOTSTRAP CLASSES HERE ) %>
<%= f.label :authorization_ids, 'Authorizations' %>

更新

这里有一些很棒的回应。我最终bootstrap_form_with使用了来自rails_bootstrap_form宝石。我使用自定义包装类进行样式设置,并且能够在井然有序的列和行中获取复选框。

<div class="container">
<div class="col">
<div class="row justify-content-center">
<div class='form-group'>
<%= bootstrap_form_with(model: @account) do |f| %>
<%= f.text_field :account_name %>
<%= f.text_field :account_address_line1 %>
<%= f.text_field :account_address_line2 %>
<%= f.text_field :account_city %>
<%= f.select :account_state, states %>
<%= f.text_field :account_zipcode %>
<%= f.text_field :contact_first_name %>
<%= f.text_field :contact_last_name %>
<%= f.email_field :contact_email %>
<%= f.telephone_field :contact_phone %>
<%= f.select :account_ppu, ppu, placeholder: "Select PPU...." %>
<%= f.text_area :account_notes %>
</div>
<%= f.collection_check_boxes :authorization_ids, Authorization.all, :id, :auth_name, hide_label: true, wrapper: {class: "cp-container-class"} %>
</div>
<%= f.submit 'Create' %>
<% end %>
</div>
</div>

造型:

@import "bootstrap";
@import "rails_bootstrap_forms";
@import url('https://fonts.googleapis.com/css?family=Baloo+Thambi+2|Lato&display=swap');
body {
margin: 0px;
}

#logo {
margin: 1em;
padding: 1em;
width: 500px;
height: auto;
}
.cp-container-class {
width: 1000px;
height: 500px;
justify-items: center; 
flex-direction:column;
padding: 10px;
/* Change to whatever*/
display: flex;
flex-wrap: wrap;
border: black 1px solid;
}
.cp-container-class>* {
flex: 1 1 20px; 
margin-left: 50px; 
letter-spacing: 5px;
}

根据collection_check_boxes的文档,您可以使用构建器添加 HTML 类,如下所示:

collection_check_boxes(:post, :author_ids, Author.all, :id, :name_with_initial) do |b|
b.label(class: "check_box") { b.check_box(class: "check_box") }
end

就您的情况而言,它看起来像这样:

collection_check_boxes(:authorization_ids, Authorization.all, :id, :auth_name, { checked: @account.try { |a| a.authorization_ids.map(&:to_param) } }, multiple: true) do |b|
b.label(class: "some-class another-class") { b.check_box(class: "a-class a-different-class") }
end

这可能不完全是你想要的;你可能不得不稍微玩一下。

最新更新