Rails 5 form_for与复选框数组 [英] Rails 5 form_for with checkbox array
问题描述
我正在使用PostgreSQL数据库和Rails 5.0.6。
我尝试为我所在的学校构建课程分配WebApp。对于每门课程,教师都可以选择允许访问该表格的表格。
I am using a PostgreSQL database and Rails 5.0.6. I try to build a course allocation WebApp for the school where I am working. For each course the teachers are able to select which forms are allowed to visit the course.
迁移文件:
def up
create_table :courses do |t|
t.integer :number, null: false
t.string :name, null: false
t.text :description, null: false
t.decimal :level, array: true, default: []
t.integer :max_visitor, null: false
t.integer :min_visitor
t.integer :pos_visit
t.timestamps
end
end
在我的控制器中:
params.require(:course).permit(:number, :name, :description, :level [], :max_visitor, :min_visitor, :pos_visits)
我已经阅读了这篇文章:使用复选框值内的Array滚动5个强参数。但是语法 params.require(:product).permit(:id,** category_ids:[] **)
对我不起作用,即使我使用rails 5作为好。我不确定:level []
是否确实有效,但是语法似乎正确。
I already read this post: Rails 5 strong params with an Array within check boxes values. But the Syntax params.require(:product).permit(:id, **category_ids: []**)
doesnt work for me even though I am using rails 5 as well. I am not sure if :level []
really works but it seems to be correct syntax.
这是我的格式:
<%= form_for @course do |t| %>
<%= t.text_field :number, class: 'form-control' %>
<%= t.text_field :name, class: 'form-control' %>
<%= t.text_area :description, class: 'form-control' %>
<%= t.check_box :level[], 1%>
<%= t.check_box :level[], 2%>
<%= t.check_box :level[], 3%>
<%= t.check_box :level[], 4%>
<%= t.text_field :max_visitor, class: 'form-control' %>
<%= t.text_field :min_visitor, class: 'form-control' %>
<%= t.text_field :pos_visit, class: 'form-control' %><br/>
<%= t.submit "bestätigen", class: "btn btn-success"%>
<% end %>
此check_box语法似乎是错误的。
有人可以通过check_boxes的正确语法帮助我吗?
感谢您的帮助。
This check_box syntax seems to be wrong. May anyone help me with the right syntax of the check_boxes? Thanks for help.
推荐答案
有一个 collection_check_boxes 辅助方法:
<%= form_for @course do |f| %>
<%= f.collection_check_boxes(:level, { 'One': 1, 'Two': 2, 'Three': 3 }, :last, :first) %>
<% end %>
第三个参数是用于从集合中获取值的方法,第四个参数是从集合中获取标签的方法。这种辅助方法会自动将哈希转换为数组,这就是为什么我在这里使用 last
和 first
的原因。
The third argument is the method used to get the value from the "collection", and the fourth is the method used to get the label from the "collection". This helper method automatically converts the Hash into an array, that's why I'm using last
and first
here.
也可以按照您想要的方式设置样式,例如使用Bootstrap:
It's also possible to style it the way you want e.g. using Bootstrap:
<%= f.collection_check_boxes(:level, { 'One': 1, 'Two': 2, 'Three': 3 }, :last, :first) do |b| %>
<div class="form-check form-check-inline">
<%= b.check_box class: 'form-check-input' %>
<%= b.label class: 'form-check-label' %>
</div>
<% end %>
这篇关于Rails 5 form_for与复选框数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!