Dan*_*n L 5 forms collections ruby-on-rails radio-button
Rails 有一个表单助手f.collection_radio_buttons,其操作与表单助手非常相似f.collection_select。
但是,f.colleciton_radio_buttons仅适用于对象集合,不适用于简单数组。
作为一个例子,我可以有:
<%= f.select :attribute, ["First", "Second"] %>
Run Code Online (Sandbox Code Playgroud)
但没有:
<%= f.radio_buttons :attribute, ["First", "Second"] %>
Run Code Online (Sandbox Code Playgroud)
因此,要使用f.collection_radio_buttons一个简单的数组,我必须这样做:
<%= f.collection_radio _buttons :attribute, ["First", "Second"], :to_s, :to_s %>
Run Code Online (Sandbox Code Playgroud)
这“有效”,但看起来很老套。有没有一种更干净的方法来引用数组的值而不是调用.to_s它?
也许这是一篇旧文章,但如果对其他人有帮助,那么就在这里。现在在 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"]]
Run Code Online (Sandbox Code Playgroud)
然后在我的表单视图中我有类似的内容:
<%= 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 %>
Run Code Online (Sandbox Code Playgroud)
它呈现出这样的效果:
HTML 看起来像这样:
<%= 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 %>
Run Code Online (Sandbox Code Playgroud)
我希望它对其他人来说是一个很好的参考。