Rails 5 - how to dynamically add to the form a nested object using autocomplete

Viewed 2371

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:

enter image description here

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 in TeamsController and Rails doesn't remember created @team, when AJAX is trying to create team_user object. To create a object of team_user model need to run @team.team_users.build(user_id: params[:user_id]). The user_id I get from autocomplete field, but don't know @team and team_id (for example, in new action TeamsController).
3 Answers
Related