如何在表单collection_select rails中将多个id作为数组传递?

roc*_*ock 6 ruby-on-rails ruby-on-rails-5

project具有 one_to_many 关联,stages并且financial
stage具有 one_to_many 关联task
task具有 one_to_many 关联sub_task

Financial#form视图中,我试图传递idcollection_select作为组合 id 的数组,例如(例如:阶段的 id,父阶段的 id。任务的 id,stage.id 的任务的 id。sub_task 的 id。 sub_task)

同样下拉首先访问所有阶段,然后在当前场景中的任务是我如何像第一阶段一样打开下拉,然后是它们对应的所有任务,然后是所有 sub_tasks?

在此处输入图片说明

代码如何识别哪个值来自哪个表,因为下拉来自基于引用的多个表

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>
Run Code Online (Sandbox Code Playgroud)

项目文件

  has_many :stages
  has_many :tasks, through: :stages
  has_many :sub_tasks, through: :tasks

Run Code Online (Sandbox Code Playgroud)

Cle*_*ler 3

所以我将如何解决这个问题:

从数据角度来看,根本不需要获取和渲染阶段和任务,因为您可以通过子任务访问该数据。因此,如果您相应地渲染选择并将子任务的 ID 存储在数据库中,您将能够从中访问任务和阶段:

<%= form.collection_select :cost_head, @project.sub_tasks, :id, :task_name, prompt: true %>
Run Code Online (Sandbox Code Playgroud)

其他任何地方:

financial.cost_head.task # => the task
financial.cost_head.task.stage # => the stage
Run Code Online (Sandbox Code Playgroud)

如果您想在选择中包含 ID 以便于选择,您可以编写自己的 ID label_method,例如:

在子任务模型中:

def full_task_name
  "#{task.stage.id}.#{task.id}.#{id} #{task_name}"
end
Run Code Online (Sandbox Code Playgroud)

然后采用以下形式:

<%= form.collection_select :cost_head, @project.sub_tasks, :id, :full_task_name, prompt: true %>
Run Code Online (Sandbox Code Playgroud)

如果排序关闭,您可能需要执行以下操作:

在控制器中:

@cost_heads = @project.sub_tasks.includes(task: :stage).order("stages.id ASC, tasks.id ASC, sub_tasks.id ASC")
Run Code Online (Sandbox Code Playgroud)

形式为:

<%= form.collection_select :cost_head, @cost_heads, :id, :full_task_name, prompt: true %>
Run Code Online (Sandbox Code Playgroud)