[英]how to pass multiple ids as an array in form collection_select rails?
project
與stages
和financial
具有 one_to_many 關聯
stage
與task
有 one_to_many 關聯
task
與sub_task
有 one_to_many 關聯。
在Financial#form視圖中,我試圖將id
作為組合 id 的數組傳遞給collection_select (例如:-id of stage,id of parent stage. id of task,id of stage.id of task.id of sub_task.id子任務)
下拉列表首先訪問所有階段,然后當前場景中的任務是我如何像第一階段一樣打開下拉列表,然后是它們對應的所有任務,然后是所有子任務?
代碼如何識別哪個值來自哪個表,因為下拉列表來自基於引用的多個表
form.html.erb(財務)
<div class="field column large-8">
<br>
<%= form.label :acitivity_Select %>
<%= form.collection_select :cost_head, @project.stages.all+ @project.tasks.all+ @project.sub_tasks.all, :id, :task_name, prompt: true %>
</div>
項目.rb
has_many :stages
has_many :tasks, through: :stages
has_many :sub_tasks, through: :tasks
所以這就是我如何解決這個問題的 go:
從數據的角度來看,根本不需要獲取和渲染階段和任務,因為您可以通過子任務訪問該數據。 因此,如果您相應地渲染 select 並將子任務的 ID 存儲在數據庫中,您將能夠從中訪問任務和階段:
<%= form.collection_select :cost_head, @project.sub_tasks, :id, :task_name, prompt: true %>
其他任何地方:
financial.cost_head.task # => the task
financial.cost_head.task.stage # => the stage
如果您想在 select 中包含 ID 以便於選擇,您可以編寫自己的label_method
,例如:
在子任務 model 中:
def full_task_name
"#{task.stage.id}.#{task.id}.#{id} #{task_name}"
end
然后在表格中:
<%= form.collection_select :cost_head, @project.sub_tasks, :id, :full_task_name, prompt: true %>
如果排序關閉,您可能需要執行以下操作:
在 controller 中:
@cost_heads = @project.sub_tasks.includes(task: :stage).order("stages.id ASC, tasks.id ASC, sub_tasks.id ASC")
在表格中:
<%= form.collection_select :cost_head, @cost_heads, :id, :full_task_name, prompt: true %>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.