问题描述
我的模特
Class Person
belongs_to :job,class: "Job"
end
Class Job
has_ancestry orphan_strategy: :adopt
end
在我看来
= form.select(:job_id,Job.all.map { |job| [job.name.titleize,job.id] },{prompt: 'Job'},{:class => 'form-control'})
当我不使用grouped_options_for_select时,可以正常使用。更新记录时我得到了数据。但我的选择选项未正确列出
= form.select :job_id,grouped_options_for_select(Job.roots.map { |parent| [parent.name,parent.children.map { |c| [c.name,c.id]}] }),{prompt: 'Select'},{class: "form-control"}
但是当我在更新记录时使用此“ grouped_options_for_select”时。作业ID没有出现在我的选择选项中
output
Parent1
child1 <----this is in the select option
child2 <----this is in the select option
Parent2
child1 <----this is in the select option
child2 <----this is in the select option
例如,我必须使用Parent2 编辑工作记录。
当我加载作业记录时,我的选择没有得到正确的记录。
选择框始终获得第一个选择选项
解决方法
检查模型。是吗?
Job.roots.map { |parent| [parent.name,parent.children.map { |c| [c.name,c.id]}] }
到
[
["Teacher",[["Physics",2],["Math",3]]],["programmer",[["junior",5],["senior",6]]]
]
但是我认为选择选项不是必需的。
它是带有选择框的表单的片段。
<%= form_for :form do |f| %>
<%= f.select(
"job_id",grouped_options_for_select(
Job.roots.map { |parent| [
parent.name,parent.children.map { |child| [child.id,child.name] }
] }
),{prompt: "Select"},{class: "form-control"}
)
%>
<% end %>
这是您想要的选择,对吧?
<select name="form[job_id]" id="form_job_id">
<option value="">Select</option>
<optgroup label="Teacher">
<option value="2">Physics</option>
<option value="3">Math</option>
</optgroup>
<optgroup label="programmer">
<option value="5">junior</option>
<option value="6">senior</option>
</optgroup>
</select>
更新的答案
首次选择“物理”选项时
grouped_options_for_select(
Job.roots.map { |parent| [
parent.name,child.name] }
] },2 <-- add selected_params value by N
)
,
- 没有grouped_options_for_select
您在使用Job.all
时,正在显示所有作业,即parents
和childern
。
- 使用grouped_options_for_select
这里您使用的是Job.roots
,然后使用parent.children
,基本上只显示了“孩子”。
要同时显示parent
和children
并显示正确的清单,您必须在grouped_options_for_select
第二个参数中添加parents数组。
= form.select :job_id,grouped_options_for_select(
Job.roots.map { |parent|
[
parent.name,[parent.name,parent.id] + parent.children.map { |c| [c.name,c.id]}
]
}
),{prompt: 'Select'},{class: "form-control"}
注意:-注意[parent.name,parent.id] +
。