チャットアプリケーション制作記録1 動作考察
class GroupsController < ApplicationController before_action :set_group, only:[:show, :edit, :update] def index @groups = current_user.groups end def new @group = Group.new end def create @group = Group.new(group_params) if @group.save redirect_to root_path, notice: 'グループが作成されました' else flash.now[:alert] = "グループ名を入力してください" render :new end end def edit end def update if @group.update(group_params) redirect_to group_path(@group), flash: {notice: 'グループ情報が変更されました。'} else render 'edit' flash[:alert] = 'グループ情報の変更に失敗しました' end end def show @groups = current_user.groups end private def group_params params.require(:group).permit(:name, { user_ids:[] }) end def set_group @group = Group.find(params[:id]) end end
各アクションの動作について
index
def index @groups = current_user.groups end
current_userに紐付いたgroupsテーブルの値を全て@groupに代入する。
%ul.chat__side_bar__groups - @groups.each do |group| %li.chat__side_bar__groups__group = link_to group_path(group.id) do %p.chat__side_bar__groups__group_name = group.name %p.chat__side_bar__groups__group_message 最新メッセージ
値は以上のように、eachで出力する。
new create
def new @group = Group.new end def create @group = Group.new(group_params) if @group.save redirect_to root_path, notice: 'グループが作成されました' else flash.now[:alert] = "グループ名を入力してください" render :new end end private def group_params params.require(:group).permit(:name, { user_ids:[] }) end
newアクションはグループ作成時に空のインスタンスを作成する。作成された情報はここに入る。
createアクションは空のインスタンスに、ストロングパラメータ取得された、:name,user_ids:[]を入れ、正しく入力されたら値を保存し、そうでない場合はnewアクションに戻す。
edit update
before_action :set_group, only:[:show, :edit, :update] def edit end def update if @group.update(group_params) redirect_to group_path(@group), flash: {notice: 'グループ情報が変更されました。'} else render 'edit' flash[:alert] = 'グループ情報の変更に失敗しました' end end def set_group @group = Group.find(params[:id]) end
編集画面に移動する際に、editアクションは入力されたidに対応する値をgroupsテーブルから持ってくる。
編集が完了した際に、updateアクションがそれらを保存する。
show
before_action :set_group, only:[:show, :edit, :update] def show @groups = current_user.groups end def set_group @group = Group.find(params[:id]) end
ログイン中のユーザーに紐付いた値をgroupsテーブルから取得し、@groupsに代入する。