自定义Rails 5 collection_radio_buttons以使用Bootstrap 4

时间:2016-07-14 19:37:08

标签: ruby-on-rails twitter-bootstrap form-for

尝试使用Bootstrap 4的表单无线电组件。

使用:

  • Rails 5
  • Bootstrap 4(bootstrap_ruby gem)

像这样:

<div class="radio">
  <label>
    <input type="radio" name="exampleRadios" id="exampleRadios1" value="option1" checked>
    Option one is this and that&mdash;be sure to include why it's great
  </label>
</div>
<div class="radio">
  <label>
    <input type="radio" name="exampleRadios" id="exampleRadios2" value="option2">
    Option two can be something else and selecting it will deselect option one
  </label>
</div>
<div class="radio disabled">
  <label>
    <input type="radio" name="exampleRadios" id="exampleRadios3" value="option3" disabled>
    Option three is disabled
  </label>
</div>

我正在尝试使用collection_radio_buttons辅助方法来实现这一点,但我没有运气。

有人能告诉我这是怎么做到的吗?提前谢谢。

目前,我有:

<div class="radio">
  <%= collection_radio_buttons(:post, :category_id, Category.all, :id, :name) do |b| %>
     <%= b.label do %>
       <%= b.radio_button %>
     <% end %>
  <% end %>
</div>

它缺少标签名称,因为我不知道如何获得标签名称。

我已经尝试label.name,但它引发了错误。

这是我目前得到的输出:

<div class="radio">
<input type="hidden" name="post[category_id]" value="">
<label for="post_category_id_1">
  <input type="radio" value="2" name="post[category_id]" id="post_category_id_30">
</label>
<label for="post_category_id_2">
  <input type="radio" value="2" name="post[category_id]" id="post_category_id_31">
</label>
<label for="post_category_id_3">
  <input type="radio" value="3" name="post[category_id]" id="post_category_id_32">
</label>
</div>

1 个答案:

答案 0 :(得分:3)

collection_radio_buttons accepts a block,您正在寻找的方法是attached() { this.workspace.size = { height: this.element.height * 5, width: this.element.width * 5 } setTimeout(() => { let components = this.element.querySelectorAll('.component'); Array.prototype.forEach.call(components, (component) => { let model = component.model; model.position = { x: component.clientLeft, y: component.clientTop }; } }, 0) }

text

如果您需要禁用选项3,则可以添加某种模型方法以检查是否应禁用它,然后在<%= collection_radio_buttons(:post, :category_id, Category.all, :id, :name) do |b| %> <div class="radio"> <%= b.label do %> <%= b.radio_button + b.text %> <% end %> </div> <% end %> 标记中添加<%= b.object.disabled? ? 'disabled' : '' %>之类的内容。与<div class="radio">调用(b.radio_button)相同。