当我创建一个新post(passengerride)时,它成功地将多个值存储在数据库中。但是,当我试图编辑post(passengerride)时,复选框将被取消选中。
这是我的表格:
apps/views/passengerrides/_form.html.erb:应用程序/视图/乘客指南:
<%= form_for @passengerride do |f| %>
......
<div class="form-group ">
<div class="control-label col-sm-2 requiredField">
<%= f.label :okwithgender, 'Driver should be:' %>
<span class="asteriskField">*</span>
</div>
<div class="col-sm-8">
<div class=" ">
<div class="checkbox">
<label class="checkbox"><input id="okwithgender" type="checkbox" value="Male" name="passengerride[okwithgender][]">Male</label>
</div>
<div class="checkbox">
<label class="checkbox"><input id="okwithgender" type="checkbox" value="Female" name="passengerride[okwithgender][]">Female</label>
</div>
<div class="checkbox">
<label class="checkbox"><input id="okwithgender" type="checkbox" value="Other" name="passengerride[okwithgender][]">Other</label>
</div>
<div class="checkbox">
<label class="checkbox"><input id="okwithgender" type="checkbox" value="Any Gender" name="passengerride[okwithgender][]">Any Gender</label>
</div>
</div>
</div>
</div>
....
<% end %>
应用程序/控制器/密码控制器:
def passengerride_params
params[:passengerride][:okwithgender] = params[:passengerride][:okwithgender].join(', ')
params.require(:passengerride).permit(:origin, :destination ... :okwithgender)
end
我想使用这个
<%= f.check_box ... %>
可以解决这个问题,但我不确定如何编写与<input id="okwithgender" type="checkbox" value="Male" name="passengerride[okwithgender][]">
最佳答案
您应该开始对表单字段使用rails表单帮助器http://guides.rubyonrails.org/form_helpers.html。
在您的情况下,我认为您应该尝试使用单选按钮来实现这一点,因为任何人都只会选择其中一个选项。
<%= f.radio_button :okwithgender, 'Male' %>
<%= f.label :okwithgender, 'Male', value: 'Male' %>
<%= f.radio_button :okwithgender, 'Female' %>
<%= f.label :okwithgender, 'Female', value: 'Female' %>
<%= f.radio_button :okwithgender, 'Other' %>
<%= f.label :okwithgender, 'Other', value: 'Other' %>
<%= f.radio_button :okwithgender, 'Any Gender' %>
<%= f.label :okwithgender, 'Any Gender', value: 'Any Gender' %>
要通过复选框多项选择来实现这一点,
f.check_box :okwithgender, {multiple: true}, 'Male'
f.label :okwithgender, 'Male', value: 'Male'
f.check_box :okwithgender, {multiple: true}, 'Female'
f.label :okwithgender, 'Female', value: 'Female'
f.check_box :okwithgender, {multiple: true}, 'Other'
f.label :okwithgender, 'Other', value: 'Other'
f.check_box :okwithgender, {multiple: true}, 'Any Gender'
f.label :okwithgender, 'Any Gender', value: 'Any Gender'