我想从check_box中获取 "0"(未选中)或 "1"(选中)的值,并将其保存为哈希值,但没有值可以保存......paper: nil我创建了 "paper "列为整数,谁能帮帮我?
以下是我的代码。
视图:
<div class="formgroup">
<%= f.label :paper, "Paper_Collection" %>
<% @paper.each do |key, value| %>
<div class="checkbox" >
<%= f.check_box :paper, {checked: false, multiple: true}, value == "1" ? "checked" : "" %><%= key %>
</div>
<% end %>
</div>
Controller:
def new
@box = Box.new
@paper = {red: 0, blue: 0, yellow: 0, green: 0, black: 0, white: 0}
....
end
def create
@box = Box.new(box_params)
@box.user_id = current_user.id
@paper = {red: 0, blue: 0, yellow: 0, green: 0, black: 0, white: 0}
...
end
private
def box_params
params.require(:box).permit(:status, :paper, :cable, reports: [])
end
我不知道你想得到什么,以及你想如何存储该散列作为一个整数在表中,但。
def new
@box = Box.new
@paper = {red: 0, blue: 0, yellow: 0, green: 0, black: 0, white: 0}
....
end
而在形式上:
<%= f.fields_for :paper do |paper_fields| %>
<div class="formgroup">
<%= paper_fields.label :paper, "Paper_Collection" %>
<% @paper.each do |key, value| %>
<div class="checkbox" >
<%= paper_fields.label key %>
<%= paper_fields.check_box key, checked: value == 1 %>
</div>
<% end %>
<% end %>
</div>
<% end %>
应该给你的参数,如:
{ "box" => { "paper" => { "red" => "0", "blue"=>"0", "yellow"=>"1", ... } } }
所以我想这是你要找的东西