前提・実現したいこと
userとteamをそれぞれ多対多の関係にして、
teamを新規作成時に
user_idとteam_idを中間テーブルとして用意したteam_usersに保存したいのですが上手くいきません
いろいろと試しているのですがどうしても中間テーブルにデータを保存できませんお助けください
該当のソースコード
ruby
1class User < ApplicationRecord 2 3 has_many :team_users, foreign_key: 'user_id' 4 has_many :teams, through: :team_users
ruby
1class Team < ApplicationRecord 2 3 has_many :team_users, foreign_key: 'team_id' 4 has_many :users, through: :team_users
ruby
1class TeamUser < ApplicationRecord 2 3 belongs_to :user 4 belongs_to :team
ruby
1class TeamsController < ApplicationController 2 3 def new 4 @team = Team.new 5 end 6 7 def create 8 team = Team.new(team_params.merge(user_id: current_user.id)) 9 if team.save 10 redirect_to teams_path, notice: "チーム登録が完了しました" 11 else 12 render new 13 end 14 15private 16 def team_params 17 params.require(:team).permit(:teamname, :area, :introduction, :image, user_ids:[]) 18 end
ruby
1<%= form_for (@team) do |f| %> 2 <%= f.text_field :teamname, placeholder: "チーム名", class: "form-control" %> 3 <%= f.text_field :area, placeholder: "活動エリア", class: "form-control" %> 4<% if @team.image.attached? %> 5 <%= image_tag team.image, :alt => "イメージ", width: '30%', height: '30%' %> 6<% end %> 7 <%= f.file_field :image, class: "form-control floating-label", placeholder: "画像アップロード" %> 8 <%= f.text_field :introduction, placeholder: "チーム紹介", class: "form-control" %> 9 <%= text_field_tag 'team[user_ids]', "#{current_user.id}", type: 'hidden' %> 10 <%= f.submit "チーム登録" %> 11<% end %>
試したこと
https://qiita.com/Kohei_Kishimoto0214/items/cb9a3d3da57708fb52c9
https://no-idea.hateblo.jp/entry/2020/06/26/172148
上記サイトを参考にしてコードを書きましたが中間テーブルには保存できませんでした
補足情報(FW/ツールのバージョンなど)
ruby 2.5.1p57
Rails 5.2.4.4
。
あなたの回答
tips
プレビュー