D
D
Diesel-nick2016-10-23 23:25:05
Ruby on Rails
Diesel-nick, 2016-10-23 23:25:05

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

team.rb
class Team < ApplicationRecord
  has_ancestry
  has_many :team_user
  has_many :users, through: :team_user
  accepts_nested_attributes_for :users, allow_destroy: true
end

team_user.rb
class TeamUser < ApplicationRecord
  belongs_to :team
  belongs_to :user
end

1. How to write teams_controller.rb correctly?
# 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

2. How to write views/teams/_form.html.erb correctly so that you can add and change team members (team_users) from the view?
...
<%= 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 %>
...

Need something similar to this form
cbebb328ba164488a42c52d519ca2f87.png
I don't quite understand how to use build and fields_for for such associations?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Nesterovich, 2016-10-27
@vanderv

You can do a multiselect named user_ids without fields_for.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question