Search code examples
ruby-on-railsmany-to-manyerbnested-forms

Nested form affecting already existing children to parent


Taking the example of spies and missions with a many to many relationship (spies can't be assigned to multiple missions and missions can have 4 or less spies assigned to it), I am able to make a nested form so I can create spies in the same form than the mission. But now, I don't want to create spies in the mission's form but instead, assign already created spies. What would be the best way to do this ?


Solution

  • Replace the part of the form that creates spies with one that fetches them by quoting a unique identifier, such as their name (or however they are known.)

    You can create the array to search through in the controller.

    @spies = Spy.all
    

    If there are only a few of them, I'd use a select tag. If there are too many for that, let the user type it in and use ajax to confirm and autocomplete it.

    <%= select(:spy, :spy_id, @spies) %>