I have 3 models - team, user and team_user (has_namy: through). In the form of edit and new team to do the ability to dynamically add members of this team with autocomplete input.
app/models/user.rb
class User < ApplicationRecord
has_many :team_users
has_many :teams, through: :team_users
accepts_nested_attributes_for :team_users, :teams, allow_destroy: true
end
app/models/team.rb
class Team < ApplicationRecord
has_many :team_users
has_many :users, through: :team_users
accepts_nested_attributes_for :team_users, allow_destroy: true, reject_if: proc { |a| a['user_id'].blank? }
end
app/models/team_user.rb
class TeamUser < ApplicationRecord
belongs_to :team
belongs_to :user
accepts_nested_attributes_for :team, :user, allow_destroy: true
end
I need something like this:
The problems that I have:
- Cocoon Gem generate only empty fields or that I will create when the template is rendered. And I need to find a user and add him to the team (in a non-editable field)
- If I use AJAX, the
@team = Team.new
runs only in a new action inTeamsController
and Rails doesn't remember created@team
, when AJAX is trying to createteam_user
object. To create a object ofteam_user
model need to run@team.team_users.build(user_id: params[:user_id])
. Theuser_id
I get from autocomplete field, but don't know@team
andteam_id
(for example, innew
actionTeamsController
).