HABTM relationship with text / hidden field for identifiers

I am creating a has_and_belongs_to_many relationship with Rails. Each group has many members, and each member can be part of many groups.

The relationships seem to be set up fine as I can use checkboxes to add relationships using this on my form:

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

      

However, I need to use a hidden field to send this relationship (I am using AJAX to retrieve them in the view) with an array of ids (for example [1, 3]

). I tried to use a textbox like this, but it doesn't save the data:

<%= f.text_field :participant_ids %>

      

When it participant_ids

saves the checkboxes and I am displaying it in the show view, it is an array of ids, but I cannot present it in this format to begin with.

Why can't I submit participant_ids

using a text / hidden field and is there a way to do this?


For reference, I have set up a junction 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 needed.

+3


source to share


1 answer


This answer worked for me. You will have to



<% @participants.each do |participant| %>
    <% f.hidden_field 'participant_ids][', :value => participant.id %>
<% end %>

      

0


source







All Articles