3

I'm creating a has_and_belongs_to_many relationship with Rails. Each group has many participants and each participant can be part of many groups.

The relationship seems to be set up ok as I can use check boxes to add relationships using this in my form:

<%= collection_check_boxes(:group, :participant_ids, @participants, :id, :name) %>

However, I need to use a hidden field to submit these relationships (I use AJAX to fetch them in the view) with an array of ids (e.g. [1, 3]). I've tried using a text field like this but it doesn't save the data:

<%= f.text_field :participant_ids %>

When participant_ids saves using the checkboxes and I output it on the show view it's an array of ids but I can't seem to submit it in that format to start with.

Why can't I submit the participant_ids using a text/hidden field and is there a way around this?


For reference I've set up the join table and the models look like this:

class Group < ActiveRecord::Base
   has_and_belongs_to_many :participants
end

class Participant < ActiveRecord::Base
  has_and_belongs_to_many :groups
end

I also modified the group controller to work with strong parameters like this:

def group_params
    params.require(:group).permit(:user_id, :purpose, :participant_ids => [])
end

I can post more code if necessary.

samlester
  • 335
  • 3
  • 18

1 Answers1

0

This answer worked for me. You will have to

<% @participants.each do |participant| %>
    <% f.hidden_field 'participant_ids][', :value => participant.id %>
<% end %>
mridula
  • 3,203
  • 3
  • 32
  • 55