Answer the question
In order to leave comments, you need to log in
Rails 5 has many through associations - how to write a controller and a view?
Good afternoon!
I made 2 main models and one table for communication:
user.rb
class User < ApplicationRecord
has_many :team_user
has_many :teams, through: :team_user
accepts_nested_attributes_for :teams
end
class Team < ApplicationRecord
has_ancestry
has_many :team_user
has_many :users, through: :team_user
accepts_nested_attributes_for :users, allow_destroy: true
end
class TeamUser < ApplicationRecord
belongs_to :team
belongs_to :user
end
# GET /teams/new
def new
@team = Team.new(parent_id: params[:parent_id])
# @team_users = @team.users.build ?
# @team_users = @team.team_users.build ?
end
# GET /teams/1/edit
def edit
# @team_users = @team.users.build ?
# @team_users = @team.team_users.build ?
end
# POST /teams
def create
@team = Team.new(team_params)
respond_to do |format|
if @team.save
format.html { redirect_to @team, success: t('.flash.success.message') }
else
format.html { render :new, danger: t('.flash.danger.message') }
end
end
end
# PATCH/PUT /teams/1
def update
respond_to do |format|
if @team.update(team_params)
format.html { redirect_to @team, success: t('.flash.success.message') }
else
format.html { render :edit, danger: t('.flash.danger.message') }
end
end
end
...
<%= form_for(@team) do |f| %>
<%= f.fields_for @ team_users do |user_f| %>
<%= user_f.select(:id, @team_users_collection.all.collect { |p| [ p.name, p.id ] }, { include_blank: true }) %>
<%= user_f.submit %>
<% end %>
<% end %>
...
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question