Search code examples
ruby-on-railscocoon-gem

Cocoon + Rails—how to access object data on form error (for dynamic fields)


I have cocoon creating association sub-forms, one of these forms has projects and codes

Setup

/ view (in slim format)
.nested-fields.subform.project-subform
  = link_to_remove_association "×", f
  #project-code-container
    .form_group
      = f.label :project_id, "Project"
      = f.select(:project_id,
        @current_projects.map { |project| [project.name, project.id] },
        {},
        { onChange: "updateCodes(this)" },
        )
    .form_group
      = f.label :project_code_id, "Code"
      = f.select(:project_code_id, @current_project_codes[1])

The second select should show a list of codes based on the index of the selected project. So if project 3 was selected, then the options for codes should be @current_project_codes[3]

Problem

When I hit a validation error on submit, the form is reloaded with the previous data already filled out (like a normal rails form). However, I don't know how to tell the project_code select which options it should load. Since this is a cocoon form, I don't have an object like @project to access the data.

I need to figure out what project was selected, so I can show the right codes.

On validation error/reload, how can I get a cocoon object's data?

p.s. I'm struggling to define this question, if you have ideas on how to make my question clearer, please let me know.


Solution

  • Credit to @arieljuod

    f.object gives the form's object with its data

    For my specific problem, this was the line that allowed a select to autopopulate with any pre-saved data:

    f.select(
      :project_code_id, 
      @current_project_codes[f.object.project_id || @current_projects.first.id]
    )