Создание команд и добавление пользователей через членов команды - PullRequest
0 голосов
/ 10 февраля 2020

Попытка выполнить sh: Создание команды и назначение пользователей в эту команду. Эти пользователи будут членами команды.

Некоторые примечания:

  • мультитенантное приложение. Приложение может приглашать пользователей, а пользователи являются частью учетной записи. В моих командах / новом представлении я могу
  • В моих командах / новом представлении я вижу всех пользователей, которые являются частью моей учетной записи. Я могу установить флажок рядом с пользователем, которого я хотел бы добавить в команду

Модели:

team.rb

class Team < ApplicationRecord
  belongs_to :account

  has_many :team_members, dependent: :destroy
  has_many :users, through: :team_members
  accepts_nested_attributes_for :team_members
end

user.rb

class User < ApplicationRecord
  has_many :team_members
  has_many :teams, through: :team_members
end

team_member.rb.rb

class TeamMember < ApplicationRecord
  belongs_to :account
  belongs_to :team
  belongs_to :user
end

Контроллер:

module Accounts
  class TeamsController < Accounts::BaseController
    before_action :set_team, only: [:show, :edit, :update, :destroy]

    def index
      @teams = current_account.teams.all.order("created_at DESC")
    end

    def new
      @team = current_account.teams.new
      @team_member = @team.team_members.build
    end

    def show
    end

    def create
      @team = current_account.teams.new(team_params)

      respond_to do |format|
        if @team.save
          @team.team_members.where(account_id: current_account.id, user_id: current_user.id).first_or_create

          format.html { redirect_to @team, notice: "Team was successfully created." }
          format.json { render :show, status: :created, location: @team }
        else
          format.html { render :new }
          format.json { render json: @team.errors, status: :unprocessable_entity }
        end
      end
    end

    private

      def set_team
        @team = current_account.teams.find(params[:id])
      end

      def team_params
        params.require(:team).permit(:name, :account_id, team_members:[])
      end
  end
end

Просмотров: команды / новые. html .erb

<section class="section">
    <%= render 'form', team: @team %>
</section>

команды / _form. html .erb

<%= simple_form_for(@team) do |f| %>
  <%= f.error_notification %>
  <form class="px-8 pt-6 pb-8 mb-4 bg-white rounded">
    <div class="mb-4">
      <div class="w-full mb-4 md:mr-2 md:mb-0">
        <label class="block mb-2 text-sm font-bold text-gray-700" for="teamName">
          Name your team
        </label>
         <%= f.input :name, autofocus: true, class: 'w-full px-3 py-2 mb-3 text-sm leading-tight text-gray-700 border rounded shadow appearance-none focus:outline-none focus:shadow-outline', label: false %>
       </div>
     </div>


     <div class="field">
       <%= f.label "Add users to team" %><br />
       <%= f.collection_check_boxes :team_members, current_account.users.all, :id, :name do |b| %>
         <div class="collection-check-box">
           <%= b.check_box %>
           <%= b.label %>
         </div>
       <% end %>
     </div>

   <div class="field">
    <div class="control">
      <%= f.button :submit, class: "w-full px-4 py-2 font-bold text-white rounded-full bg-green-500 hover:bg-green-700 focus:outline-none focus:shadow-outline" %>
    </div>
   </div>
  </form>
<% end %>

Еще несколько заметок:

В моем контроллере. Вы заметите, что у меня есть строка в методе создания, чуть ниже save

@team.team_members.where(account_id: current_account.id, user_id: current_user.id).first_or_create

Это создает TeamMembers в моей базе данных для текущего пользователя. Однако я также хотел бы добавить пользователей, которых я выбираю в своей форме, для добавления в качестве TeamMembers.

Быстрое обновление

ActiveRecord :: AssociationTypeMismatch в Аккаунтах :: TeamsController # создать командного игрока (# 70366319660620) ожидалось, получил "", который является экземпляром String (# 70366253145620)

Параметры:

1055 * { "authenticity_token" => "YCE3KxoOgFPSCc2H1olmfpKiorf2wY7XlCFJXisa5Va / Yi3z0fy2QCny45TB8rgUij9 + 1tV7U8CmtACK1cxgOg == "," team "=> {" name "=>" Это тест "," team_members "=> [" "," 5 "]}," commit "=>« Создать команду »}

ПРИМЕЧАНИЕ, однако, если я удаляю team_members: [] из параметров, запись сохраняет текущего пользователя в базу данных для члена команды

Дополнительное редактирование

Из комментариев ниже я сейчас использую

def create
      team_members = User.find(team_params[:team_members])
      @team = current_account.teams.new(team_params.merge(users: team_members))

      respond_to do |format|
        if @team.save
          @team.team_members.where(account_id: current_account.id, user_id: current_user.id).first_or_create

          format.html { redirect_to @team, notice: "Team was successfully created." }
          format.json { render :show, status: :created, location: @team }
        else
          format.html { render :new }
          format.json { render json: @team.errors, status: :unprocessable_entity }
        end
      end
    end

и в представлении я установил include_hidden: false

Получаю следующую ошибку:

ActiveRecord :: AssociationTypeMismatch в Аккаунтах :: TeamsController # create TeamM Ожидается, что ember (# 70366305317040), получил "5", который является экземпляром String (# 70366253145620)

Следующее обновление

Использование: @team = current_account.teams. new (team_params.except (: team_members) .merge (пользователи: team_members)

Started POST "/teams" for 127.0.0.1 at 2020-02-09 17:29:59 -0500
17:29:59 web.1     | Processing by Accounts::TeamsController#create as HTML
17:29:59 web.1     |   Parameters: {"authenticity_token"=>"Pe+gDCggvkbeLcv0HiYr6LI52mnz89jtpVQSM9mf8mgIypqdEVn4yhlp6rEI9n4U7ijQHX4or9T8rPF5v8a5lw==", "team"=>{"name"=>"This is a test", "team_members"=>["5"]}, "commit"=>"Create Team"}
17:29:59 web.1     |   User Load (0.3ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 2], ["LIMIT", 1]]
17:29:59 web.1     |   ↳ app/controllers/accounts/base_controller.rb:18:in `authorize_user!'
17:29:59 web.1     |   Account Load (0.3ms)  SELECT "accounts".* FROM "accounts" WHERE "accounts"."subdomain" = $1 LIMIT $2  [["subdomain", "diplomat"], ["LIMIT", 1]]
17:29:59 web.1     |   ↳ app/controllers/accounts/base_controller.rb:6:in `current_account'
17:29:59 web.1     |   User Load (0.3ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2  [["id", 2], ["LIMIT", 1]]
17:29:59 web.1     |   ↳ app/controllers/accounts/base_controller.rb:19:in `authorize_user!'
17:29:59 web.1     |    (0.9ms)  BEGIN
17:29:59 web.1     |   ↳ app/controllers/accounts/teams_controller.rb:23:in `block in create'
17:29:59 web.1     |   Team Create (1.4ms)  INSERT INTO "teams" ("name", "account_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id"  [["name", "This is a test"], ["account_id", 2], ["created_at", "2020-02-09 22:29:59.577691"], ["updated_at", "2020-02-09 22:29:59.577691"]]
17:29:59 web.1     |   ↳ app/controllers/accounts/teams_controller.rb:23:in `block in create'
17:29:59 web.1     |    (0.5ms)  COMMIT
17:29:59 web.1     |   ↳ app/controllers/accounts/teams_controller.rb:23:in `block in create'
17:29:59 web.1     |   TeamMember Load (0.7ms)  SELECT "team_members".* FROM "team_members" WHERE "team_members"."team_id" = $1 AND "team_members"."account_id" = $2 AND "team_members"."user_id" = $3 ORDER BY "team_members"."id" ASC LIMIT $4  [["team_id", 37], ["account_id", 2], ["user_id", 2], ["LIMIT", 1]]
17:29:59 web.1     |   ↳ app/controllers/accounts/teams_controller.rb:24:in `block in create'
17:29:59 web.1     |    (0.3ms)  BEGIN
17:29:59 web.1     |   ↳ app/controllers/accounts/teams_controller.rb:24:in `block in create'
17:29:59 web.1     |   Account Load (0.9ms)  SELECT "accounts".* FROM "accounts" WHERE "accounts"."id" = $1 LIMIT $2  [["id", 2], ["LIMIT", 1]]
17:29:59 web.1     |   ↳ app/controllers/accounts/teams_controller.rb:24:in `block in create'
17:29:59 web.1     |   User Load (1.2ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2  [["id", 2], ["LIMIT", 1]]
17:29:59 web.1     |   ↳ app/controllers/accounts/teams_controller.rb:24:in `block in create'
17:29:59 web.1     |   TeamMember Create (2.3ms)  INSERT INTO "team_members" ("account_id", "team_id", "user_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id"  [["account_id", 2], ["team_id", 37], ["user_id", 2], ["created_at", "2020-02-09 22:29:59.609437"], ["updated_at", "2020-02-09 22:29:59.609437"]]
17:29:59 web.1     |   ↳ app/controllers/accounts/teams_controller.rb:24:in `block in create'
17:29:59 web.1     |    (0.7ms)  COMMIT
17:29:59 web.1     |   ↳ app/controllers/accounts/teams_controller.rb:24:in `block in create'
17:29:59 web.1     | Redirected to http://diplomat.lvh.me:5000/teams/37
17:29:59 web.1     | Completed 302 Found in 61ms (ActiveRecord: 10.0ms | Allocations: 13997)
17:29:59 web.1     | 
17:29:59 web.1     | 
17:29:59 web.1     | Started GET "/teams/37" for 127.0.0.1 at 2020-02-09 17:29:59 -0500
17:29:59 web.1     | Processing by Accounts::TeamsController#show as HTML
17:29:59 web.1     |   Parameters: {"id"=>"37"}
17:29:59 web.1     |   User Load (0.6ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 2], ["LIMIT", 1]]
17:29:59 web.1     |   ↳ app/controllers/accounts/base_controller.rb:18:in `authorize_user!'
17:29:59 web.1     |   Account Load (0.3ms)  SELECT "accounts".* FROM "accounts" WHERE "accounts"."subdomain" = $1 LIMIT $2  [["subdomain", "diplomat"], ["LIMIT", 1]]
17:29:59 web.1     |   ↳ app/controllers/accounts/base_controller.rb:6:in `current_account'
17:29:59 web.1     |   User Load (0.4ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2  [["id", 2], ["LIMIT", 1]]
17:29:59 web.1     |   ↳ app/controllers/accounts/base_controller.rb:19:in `authorize_user!'
17:29:59 web.1     |   Team Load (0.6ms)  SELECT "teams".* FROM "teams" WHERE "teams"."account_id" = $1 AND "teams"."id" = $2 LIMIT $3  [["account_id", 2], ["id", 37], ["LIMIT", 1]]
17:29:59 web.1     |   ↳ app/controllers/accounts/teams_controller.rb:38:in `set_team'
17:29:59 web.1     |   Rendering accounts/teams/show.html.erb within layouts/application
17:29:59 web.1     |   Rendered accounts/teams/show.html.erb within layouts/application (Duration: 0.1ms | Allocations: 4)
17:29:59 web.1     |   Rendered shared/_head.html.erb (Duration: 27.7ms | Allocations: 10259)
17:29:59 web.1     |   Rendered shared/_userselect.html.erb (Duration: 0.7ms | Allocations: 319)
17:29:59 web.1     |   Rendered shared/_navbar.html.erb (Duration: 4.3ms | Allocations: 575)
17:29:59 web.1     |   Rendered shared/_notices.html.erb (Duration: 0.1ms | Allocations: 33)
17:29:59 web.1     |   Announcement Load (0.5ms)  SELECT "announcements".* FROM "announcements" ORDER BY "announcements"."published_at" DESC LIMIT $1  [["LIMIT", 1]]
17:29:59 web.1     |   ↳ app/helpers/announcements_helper.rb:3:in `unread_announcements'
17:29:59 web.1     |   Rendered shared/_footer.html.erb (Duration: 9.8ms | Allocations: 843)
17:29:59 web.1     | Completed 200 OK in 61ms (Views: 43.8ms | ActiveRecord: 2.4ms | Allocations: 15711)
17:29:59 web.1     | 
17:29:59 web.1     | 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...