Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass multiple ids as an array in form collection_select rails?

project has one_to_many association with stages and financial
stage has one_to_many association with task
task has one_to_many association with sub_task.

In Financial#form view i am trying to pass id to collection_select as an array of combined ids like (eg:-id of stage, id of parent stage . id of task, id of stage.id of task. id of sub_task . id of sub_task)

Also drop-down first accesses all stages then task in current scenario is how can i turn drop-down like first stages then their corresponding all task followed by all sub_tasks?

enter image description here

How can code identify which value is from which table, because drop-down comes from multiple table based on reference

form.html.erb (Finacial)

<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>

project.rb

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

like image 570
rock Avatar asked Jul 10 '20 05:07

rock


1 Answers

So here's how I'd go about solving this:

From a data perspective, there's no need to fetch and render the stages and tasks at all, because you can access that data via the sub tasks. So if you render the select accordingly and store the sub task's ID in the database, you'll be able to access the task and stage from it:

<%= form.collection_select :cost_head, @project.sub_tasks, :id, :task_name, prompt: true %>

Anywhere else:

financial.cost_head.task # => the task
financial.cost_head.task.stage # => the stage

If you want to include IDs in the select for easier selection, you can write your own label_method, e.g. like so:

In the SubTask model:

def full_task_name
  "#{task.stage.id}.#{task.id}.#{id} #{task_name}"
end

And then in the form:

<%= form.collection_select :cost_head, @project.sub_tasks, :id, :full_task_name, prompt: true %>

If the sorting is off, you might need to do something like this:

In the controller:

@cost_heads = @project.sub_tasks.includes(task: :stage).order("stages.id ASC, tasks.id ASC, sub_tasks.id ASC")

In the form:

<%= form.collection_select :cost_head, @cost_heads, :id, :full_task_name, prompt: true %>
like image 137
Clemens Kofler Avatar answered Nov 12 '22 11:11

Clemens Kofler