###実現したいこと
グループ機能を実装させたい。
現状、グループ機能の作成を完了しましたが、以下で手詰まりしています。
・グループにuserを所属させる。
おそらくgroup_user Modelに所属する人(user)と所属先(group)を代入すると考えています。その場合、group_userのControllerを作成し、createするのかなと思いましたが、参考サイトにはControllerの作成はないので、どのようにすべきか悩んでいます。user.rbで、has_many :groups, through: :group_usersと記載しているのですが、何らかの方法で摘出できるのかともわからずにいます。
→group/showにて、所属メンバーを一覧させますのが目的です。
参考サイト
https://qiita.com/savaniased/items/ce7dd5a825ad0f6be53c
###コード
Terminal
1$ rails g controller groups 2$ rails g model group 3$ rails g model group_user
migration
1class CreateGroups < ActiveRecord::Migration[5.2] 2 def change 3 create_table :groups do |t| 4 t.string :name 5 t.integer :user_id 6 t.text :content 7 t.timestamps 8 end 9 end 10end
migration
1class CreateGroupUsers < ActiveRecord::Migration[5.2] 2 def change 3 create_table :group_users do |t| 4 t.references :group, foreign_key: true 5 t.references :user, foreign_key: true 6 t.timestamps 7 end 8 end 9end
routes
1resources :groups, only: [:index, :new, :create, :edit, :update]
model
1#group.rb 2class Group < ApplicationRecord 3 has_many :group_users 4 has_many :users, through: :group_users 5end 6#group_user.rb 7class GroupUser < ApplicationRecord 8 belongs_to :group 9 belongs_to :user 10end 11#user.rb 12class User < ApplicationRecord 13 has_many :group_users 14 has_many :groups, through: :group_users 15end
Controller
1class GroupsController < ApplicationController 2 def index 3 @groups = Group.all 4 end 5 def new 6 @group = Group.new 7 @group.users << @current_user 8 end 9 10 def create 11 @group = Group.new( 12 name: params[:name], 13 user_id: @current_user.id, 14 content: params[:content]) 15 if @group.save 16 flash[:notice] = "新しいグループを作成しました" 17 redirect_to("/groups/") 18 else 19 render :new 20 end 21 end 22 23 private 24 def group_params 25 params.require(:group).permit(:name, :user_id, :content) 26 end 27end
回答1件
あなたの回答
tips
プレビュー