はじめに
プログラミングを学習してから1ヶ月半ほどが経ちました。
スクールでのカリキュラムも終了し、オリジナルアプリを作成しました。
私が作成したアプリの中で、グループ機能を実装したかったので今回まとめてみました。
少しづつ投稿していこうと思うので時間がかかると思いますが、お願いします。
※初めての投稿なのでMarkdown形式の記述方法にも慣れておらず、見づらいところが多いかもしれません。
グループ作成
今回は、在庫管理(探し物を見つけ出す)アプリを作成しました。
この記事ではグループを作成するところまで紹介したいと思います。
初心者のため、間違っているところがあると思いますが、ご指摘いただけると幸いです。
※@ki_87(kei i)さんの記事を参考に作成しました。
とても分かりやすく参考になりました。
ありがとうございます。
前提条件
ユーザー管理機能については実装済みで話を進めていきます。
ユーザー管理機能実装してから作成をお願いします。
また、viewについてはオリジナリティが求められるため、省略しています。
※Rails7で作成しています。
それでは作成に取り掛かります!
みなさん一緒に頑張りましょう!!!
ER図を考える
グループ機能を実装するためには、uesrsとgroupsの関係が多対多の関係になります。
多対多のアソシエーションの場合は、中間テーブル(group_users)が必要になります。
Let's start!!!
モデルとコントローラーの作成
$ rails g controller groups
$ rails g model group
$ rails g model group_user
group_userは中間テーブルなので、モデルのみの作成で大丈夫です。
マイグレーションファイルの中身
class CreateGroups < ActiveRecord::Migration[7.0]
def change
create_table :groups do |t|
t.string :group_name, null: false
t.text :introduction, null: false
t.integer :owner_id, null: false
t.references :user, foreign_key: true
t.timestamps
end
end
end
class CreateGroupUsers < ActiveRecord::Migration[7.0]
def change
create_table :group_users do |t|
t.references :user, foreign_key: true
t.references :group, foreign_key: true
t.timestamps
end
end
end
マイグレーションファイル中身が書けたのでマイグレートしましょう!
$ rails db:migrate
モデルにアソシエーションを記述
class Group < ApplicationRecord
has_many :group_users
has_many :users, through: :group_users
has_one_attached :group_image
end
グループ作成時にグループ画像を使いたいのでhas_one_attached :group_image
をアソシエーションに加えています。
※Active storage
を使用しています。
class GroupUser < ApplicationRecord
belongs_to :user
belongs_to :group
end
group_userからみてuserとgroupは1対多の関係なのでbelongs_to
を使用します。
class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_many :group_users
has_many :groups, through: :group_users
end
userモデルは上記の記述になります。
ルーティングの設定
Rails.application.routes.draw do
devise_for :users
root to: "groups#index"
resources :groups
end
resources :groups
と記述することでrailsの7つのアクションを使用することができます。
コントローラーの作成
class GroupsController < ApplicationController
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
private
def group_params
params.require(:group).permit(:group_name, :introduction, :group_image).merge(user_id: current_user.id)
end
end
ポイントはcreateアクションの@group.owner_id = current_user.id
です。
この記述をすることで、グループ作成者をowner_idとして設定しています。
終わりに
みなさん実装お疲れさまでした!
上記の内容でグループの作成はできたかと思います。
不足している箇所やわかりにくい点があったかと思いますが、最後までお付き合いいただきありがとうございました!
引き続き、グループ作成機能について投稿していきますのでよろしくお願いします!!!