ruby-on-railsrubyselectactiveadminformtastic

Formtastic in activeadmin: Is there a way to create multiple join records with a select input with multiple: true for the associated model?


I've seen many similar questions to this one, but none that quite answer it. I have a form that has an input for a join model. I've successfully created several of these with single inputs, but I'm trying to create one in which the user can select multiple from a dropdown of the associated record and create join records for each one selected. It's not working, and it appears the params are trying to assign all of the associated model ids to a single join record.

class AdminUser < ApplicationRecord
  has_many :admin_locations, dependent: :destroy
  has_many :locations, through: :admin_locations
end

class AdminLocation < ApplicationRecord
  belongs_to :admin_user
  belongs_to :location
end

class Location < ApplicationRecord
 has_many :admin_locations, dependent: :destroy
 has_many :admin_users, through: :admin_locations
end

#in the admin_users edit form
f.has_many :admin_locations,
           allow_destroy: true do |l|
           l.input :location_id,
                   as: :select,
                   include_hidden: false,
                   multiple: true,
                   collection: locs

#in admin/admin_user permitted params
admin_location_ids: [],
admin_locations_attributes: [:id, :location_id, :admin_user_id, :_destroy, :_create, :_update]

I've permitted all the params through the admin/ file, but I'm still getting the error on rollback that location_id is not a permitted param in the admin_locations form. The params show that all selected ids are getting assigned to a single join record: "admin_locations_attributes"=>{"0"=>{"location_id"=>["236", "238", "239", "241"]}}} Is there any way to make this work?


Solution

  • Oh, wow, thanks Ryan Bates. Found a decade old rails cast that answered this. I was over-complicating it.

    this works:

    f.input :locations,
            allow_destroy: true,
            as: :select,
            include_hidden: false,
            multiple: true,
            collection: locs
    

    No need for the join nesting in the form.