对于rails中的下拉值,我们可以像键值对一样编写。例如
<div class="custom-dropdown big">
<%= f.select :product_type, [["Car","Car"], ["Bus","Bus"], ["Truck","Truck"],["Flight","Flight"], ["Train","Train"], ["Ship","Ship"],
["other","other"]], id: "product_type", prompt: "Select...", class: "form-control" %>
</div>
但我们怎样才能用单选按钮做同样的事情?例如。假设我们这样的收音机按钮很少......
<div class="segmented-control" style="width: 100%; color: #5FBAAC">
<input type="radio" name="pieces" id="1">
<input type="radio" name="pieces" id="2">
<input type="radio" name="pieces" id="3">
<input type="radio" name="pieces" id="4">
<input type="radio" name="pieces" id="5">
<input type="radio" name="pieces" id="6">
<label for="1" data-value="1">1</label>
<label for="2" data-value="2">2</label>
<label for="3" data-value="3">3</label>
<label for="4" data-value="4">4</label>
<label for="5" data-value="5">5</label>
<label for="6" data-value="6 or more">6</label>
</div>
有人能告诉我如何使用rails实现同样的目标吗?
答案 0 :(得分:1)
尝试单选按钮收集:
<%= f.collection_radio_buttons :product_type, [["Car","Car"], ["Bus","Bus"], ["Truck","Truck"],["Flight","Flight"], ["Train","Train"], ["Ship","Ship"],
["other","other"]], :first, :last %>
答案 1 :(得分:1)
键值对
你拥有的数组 - key-value pairs是“哈希”,并且显示如下:
[
{id: "1", name: "car"},
{id: "2", name: "bus"},
{id: "3", name: "truck"},
{id: "4", name: "flight"},
{id: "5", name: "train"},
{id: "6", name: "ship"},
{id: "7", name: "other"}
]
如果你有以下内容,那就可以了:
#app/controllers/your_controller.rb
class YourController < ApplicationController
def index
@transports = [{id: "1", name: "car"},{id: "2", name: "bus"},{id: "3", name: "truck"},{id: "4", name: "flight"},{id: "5", name: "train"},{id: "6", name: "ship"},{id: "7", name: "other"}]
end
end
#app/views/your_controller/index.html.erb
<%= f.collection_radio_buttons :product_type, @transports, :id, :name %>
使用您当前的设置,您应该能够使用以下内容:
class YourController < ApplicationController
def index
@transports = [["Car","Car"],["Bus","Bus"],["Truck","Truck"],["Flight","Flight"],["Train","Train"],["Ship","Ship"],["other","other"]]
end
end
#app/views/your_controller/index.html.erb
<%= f.select :product_type, options_for_select(@transports), id: "product_type", prompt: "Select...", class: "form-control" %>