@Diesel-nick

Rails 5 has many through associations — как правильно написать контроллер и вьюху?

Добрый день!

Сделал 2-е основные модели и одну таблицу для связи:

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. Как правильно написать teams_controller.rb?
# 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. Как правильно написать views/teams/_form.html.erb, чтоб из вьюхи можно было добавлять и изменять участников команды (team_users)?
...
<%= 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 %>
...


Нужно что-то похожее на эту форму
cbebb328ba164488a42c52d519ca2f87.png
Не совсем понимаю как использовать build и fields_for для таких ассоциаций?
  • Вопрос задан
  • 363 просмотра
Пригласить эксперта
Ответы на вопрос 1
@vanderv
Ruby on Rails
Можешь сделать мультиселект с именем user_ids без fields_for.
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы