htmlruby-on-railsruby-on-rails-5ancestry

Rails 'grouped_options_for_select' edit not working


My model

Class Person
   belongs_to :job, class: "Job"
end

 Class Job
    has_ancestry orphan_strategy: :adopt
end

in my view

= form.select(:job_id, Job.all.map { |job| [job.name.titleize, job.id] }, {prompt: 'Job'}, {:class => 'form-control'})

when I use without grouped_options_for_select its working fine. I get the data when updating the record. but my select option is not listing properly

= 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"}

but when I use this 'grouped_options_for_select' when updating the record. the job id not appearing in my select option

 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

for example, I have to edit the record of a job with Parent2<<Child2.

when I load the Job record my select is not getting the right record.

the select box always get the first select option


Solution

  • Check your model. is it right?

    Job.roots.map { |parent| [parent.name, parent.children.map { |c| [c.name, c.id]}] }

    to

    [
        ["Teacher", [["Physics", 2], ["Math", 3]]], 
        ["programmer", [["junior", 5], ["senior", 6]]]
    ]
    

    But I think Person is not necessary for select's options.

    It is snippet for form with select box.

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

    And it is select you want, right?

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

    updated answer

    when you first select 'Physics' option

      grouped_options_for_select(
        Job.roots.map { |parent| [
          parent.name,
          parent.children.map { |child| [child.id, child.name] }
        ] },
        2  <-- add selected_params value by N
      )