I did some research and found this(Update multiple checkboxes on association model through nested attributes with Cocoon gem in Rails) but my case is a bit different i assume.
Suppose I have 3 models: User, Client, Role. The relation is many_to_many through assignments between User & Client and same many_to_many through assignments between User and Role.
class User < ApplicationRecord
has_many :assignments, inverse_of: :user, :dependent => :destroy
has_many :roles, through: :assignments
accepts_nested_attributes_for :assignments, reject_if: :all_blank, allow_destroy: true
end
class Client < ApplicationRecord
has_many :assignments, inverse_of: :client, :dependent => :destroy
has_many :users, through: :assignments
end
class Role < ApplicationRecord
has_many :assignments, inverse_of: :role, :dependent => :destroy
has_many :users, through: :assignments
end
Join table Assignment
class Assignment < ApplicationRecord
belongs_to :user
belongs_to :role
belongs_to :client
end
Assignment table contains user_id, role_id, client_id
My views:
form.html.erb
<%= f.fields_for :assignments,url: url do |assignment_form| %>
<%= render partial: 'users/assignment_fields', locals: { f: assignment_form,user: @user } %>
<% end %>
<div>
<%= link_to_add_association "Add", f, :assignments, partial: 'users/assignment_fields',render_options: { locals:{ user: @user } } %>
</div>
</div>
_assignment_fields.html.erb
<%= f.collection_check_boxes :role_id, Role.all, :id, :short_name, html_options = {} %>
params permit:
[:first_name, :last_name,assignments_attributes: [:client_id, role_id: [] ] ]
params in console.
"user"=><ActionController::Parameters {"first_name"=>"a", "last_name"=>"d", "assignments_attributes"=><ActionController::Parameters {"0"=><ActionController::Parameters {"client_id"=>"2", "role_id"=>["2", "4"], "id"=>"300"}
Now what i need to do is save the User form along with the fields shown below in the link screenshot. The below shown fields needs to be saved in the Assignments join table.Note: I am using cocoon to add more records.
I want know how can I save the role_ids that come to the Assignment which means if we have 2 roles for a client then 2 different records needs to be created in the join assignment table.
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/bAvfe.png [Screenshot link]