0
0

【Ruby on rails】グループ作成 その2 グループ参加と退出

Last updated at Posted at 2023-10-06

はじめに

プログラミングを勉強して2か月ほどです。
初心者なので間違っているところがあれば、ご指摘いただけると幸いです。
@ki_87(kei i)さんの記事を参考に作成しました。
 とても分かりやすく参考になりました。
 ありがとうございます。

グループの参加と退出

今回は作成したグループへの参加と退出を実装していきます。
グループの作成については下記の記事で行っています。

それでは作成していきましょう!!!

Let's start!!!

ルーティングの設定

routes.rb
Rails.application.routes.draw do
  devise_for :users
  root to: "groups#index"
  resources :groups do
    get "join" => "groups#join"
    delete "exit" => "groups#exit"
  end
end

コントローラーの記述

groups.controller.rb
class GroupsController < ApplicationController
  
  before_action :set_group, only: [:show, :edit, :update, :destroy]

  def index
    @groups = Group.all
  end

  def new
    @group = Group.new
  end

  def create
    @group = Group.new(group_params)
    @group.owner_id = current_user.id
    if @group.save
      redirect_to root_path
    else
      render :new, status: :unprocessable_entity
    end
  end

  def show
  end

  def join
    @group = Group.find(params[:group_id])
    unless @group.users.include?(current_user)
      @group.users << current_user
    end
  end

  def update
    if @group.update(group_params)
      redirect_to group_path(@group)
    else
      render :edit, status: :unprocessable_entity
    end
  end

  def exit
    @group = Group.find(params[:group_id])
    @group.users.delete(current_user)
    redirect_to root_path
  end

  private

  def group_params
    params.require(:group).permit(:group_name, :introduction, :group_image).merge(user_id: current_user.id)
  end

  def set_group
    @group = Group.find(params[:id])
  end
end

@group.users << current_user
この記述により、@group.usersにcurrent_userを追加しています。
<<はシフト演算子と言われる演算子のようです。
私も詳しくは説明できませんが、<<の記述であれば右に書かれた記述が左にシフトする(左に追加される)というイメージで問題ないと思います。

before_action :set_group, only: [:show, :edit, :update, :destroy]
この記述は@group = Group.find(params[:id])が複数のアクションで使用されているのでset_groupにまとめてbefore_actionで呼び出しています。

Rails7での注意点

退出ボタンを実装する際に注意点が必要です。
<%= link_to "Exit", group_exit_path(group.id), data: { turbo_method: :delete }, class: "btn btn-purple mx-3" %>
上記の記述の中でdata: { turbo_method: :delete }がポイントになります。
Rails7より前のバージョンではmethod: :deleteという記述でdestoroyアクションが実行されたようですが記述方法が変わっているので注意です!

data: { turbo_method: :delete }とは

そもそも、なぜdestroyアクションが実行されるときにdata: { turbo_method: :delete }という記述が必要なのか?
この記述をしないと、httpメソッドのgetが呼び出されてしまうからのようです。data: { turbo_method: :delete }と記述することでdeleteが呼び出されます。

終わりに

みなさん実装お疲れ様でした!!!
グループへの参加と退出が実装出来たかと思います。
分かりづらい点が多かったと思いましたが、最後まで読んでいただきありがとうございました!!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0