Rails有一个表单助手f.collection_radio_buttons
,其操作与f.collection_select
表单助手非常相似。
但是,f.colleciton_radio_buttons
仅适用于对象集合,并且不适用于简单数组。
举个例子,我可以:
<%= f.select :attribute, ["First", "Second"] %>
但是没有:
<%= f.radio_buttons :attribute, ["First", "Second"] %>
所以要使f.collection_radio_buttons
使用一个简单的数组,我必须这样做:
<%= f.collection_radio _buttons :attribute, ["First", "Second"], :to_s, :to_s %>
这&#34;工作&#34;但它似乎非常hacky。是否有更简洁的方法来引用数组的值而不是在其上调用.to_s
?
答案 0 :(得分:0)
也许这是一篇过时的文章,但是如果它对其他人有帮助,那就在这里。现在,在2019年,我正在使用 Rails 5 应用程序,并且我有一个表单必须在其中显示给定属性的两个单选按钮。
我是一个辅助方法:
def get_company_segments
company = current_user.branch.company
[
[company.various_segment_fee, 'various', 'Varios'],
[company.metal_segment_fee, 'metal', 'Metal']
]
end
Output:
#=> [["12.6", "various", "Varios"], ["10", "metal", "Metal"]]
然后在表单视图中,我会看到类似的内容
:<%= form.collection_radio_buttons(:segment, get_company_segments, :second, :last) do |segment| %>
<div class="form-check form-check-inline">
<%= segment.radio_button(class: 'form-check-input', id: "agreement_segment_#{segment.object.second}" %>
<%= segment.label(class: 'form-check-label', for: "agreement_segment_#{segment.object.second}") %>
</div>
<%- end %>
它呈现出如下内容:
HTML如下所示:
<div class="form-check custom-radio form-check-inline">
<input class="form-check-input" id="agreement_segment_various" data-fee="12.6" type="radio" value="various" name="agreement[segment]">
<label class="form-check-label" for="agreement_segment_various">Varios</label>
</div>
<div class="form-check custom-radio form-check-inline">
<input class="form-check-input" id="agreement_segment_metal" data-fee="10" type="radio" value="metal" name="agreement[segment]">
<label class="form-check-label" for="agreement_segment_metal">Metal</label>
</div>
我希望它可以为其他任何人提供很好的参考。 ?