Search code examples
ruby-on-railsactiveadminhas-and-belongs-to-many

How to assign one model's record to another associated record in active admin?


I have an app which registers applicants as Participants and then assigns them to Groups. The two models are associated via has_and_belongs_to_many relationship. There are other hanging models related to Participant, but they are not connected to Groups.

I'd like to be able to assign a Participant to a Group when I create a new Group in active admin.

My two models are joined through a join table called matchups.

My Group model schema is as follows:

    create_table "groups", force: :cascade do |t|
t.string   "description"
t.integer  "participant_id"
t.datetime "created_at",     null: false
t.datetime "updated_at",     null: false
t.index ["participant_id"], name: "index_groups_on_participant_id"
   end

My Participant model schema is as follows:

    create_table "participants", force: :cascade do |t|
t.string   "first_name"
t.string   "last_name"
t.date     "birthdate"
t.string   "email"
t.string   "phone"
t.string   "street_name"
t.string   "city"
t.string   "state"
t.string   "zip"
t.string   "role"
t.datetime "created_at",  null: false
t.datetime "updated_at",  null: false
t.string   "gender"
   end 

My active admin resources allow the following params: For Groups:

    permit_params :id, :description, :participant_id, :student_detail_id, :volunteer_detail_id

For Participants:

    permit_params :id, :first_name, :last_name, :gender, :email, :birthdate, :phone, :street_name, :city, :state, :zip, :role

When I got to create a new Group in active admin, the only field I am able to fill out is :description.

I'd like to assign the new group to one or more :participant_id.


Solution

  • write a custom form in admin/groups.rb to accept multiple participant_ids like below

    ActiveAdmin.register Group do
    permit_params :description , participant_ids: []
      form do |f|
        f.inputs 'Group Details' do
          f.input :description
          f.input :participant_ids, as: :check_boxes, collection: Participant.all
         end
      end
    end