LoginSignup
2
4

More than 1 year has passed since last update.

[Ruby on rails]グループ作成機能③グループ管理者/作成者の表示 class_nameオプション

Posted at

初めに

①②の記事で、グループ作成、参加、退会を実装してきました。
今回その続きです。
:sunny:注意①②と③④で作ってるアプリが違います。
①②は本の投稿(bookモデル)サイトでの、グループ作成機能。
③④は記事の投稿(postモデル)サイトでの、グループ作成機能です。
①②と③④でGroupのカラムが若干違います。
グループ名(name)、
グループ紹介(introduction)
オーナーid(owner_id)は共通ですが、
①②では、t.string :image_idがあるのに対し、
③④では、image_idが無く、t.string :status(参加条件)を
付け足しています。

行う作業自体は変わりませんが、少しややこしいかもしれません...

やりたいこと

以下のように、グループ管理者を表示させたいです。
今回の場合は、山田たお さんです。

スクリーンショット 2021-08-03 22.41.53.png

正直、大変でした!!!全然、分からず、できず......

マイグレーションファイルの編集

Groupのマイグレーションファイル
class CreateGroups < ActiveRecord::Migration[5.2]
  def change
    create_table :groups do |t|
      t.string :name,null: false
      t.text :introduction,null: false
      t.integer :owner_id
      t.string :status
      t.references :user
      t.timestamps
    end
  end
end

①グループテーブルにuserの外部キーを記載しました。
Group:User は1:N
User:Groupは1:Nなので、GroupUserという中間テーブルを作成してますが、
グループの作成者については、作成者はグループに「1人」なので、
別でリレーションを書くことができるんですね:point_up:

モデルファイル編集

group.rb
class Group < ApplicationRecord
  has_many :group_users
  # グループは複数のユーザーを持つ。group_usersから参照可能
  has_many :users, through: :group_users,dependent: :destroy
  # グループオーナー表示のために
  belongs_to :user
省略
group.rb
class Group < ApplicationRecord
  has_many :group_users
  # グループは複数のユーザーを持つ。group_usersから参照可能
  has_many :users, through: :group_users,dependent: :destroy
  # グループオーナー表示のために
  belongs_to :user
省略
user.rb
# グループのアソシエーション
  has_many:group_users
  # group_usersは中間テーブル
  has_many:groups, through: :group_users,dependent: :destroy
  # グループオーナー表示のため
  has_many :owned_groups, class_name: "Group"
省略

has_many :owned_groups, class_name: "Group"は、
正直に書くと、has_many :groupsです。
しかしながら、すでにその記述はしているので、出来ません。
なので、グループとグループオーナーの関係は、class_nameを使用して書きます。
これでユーザー1に紐づくグループ、ユーザー1に紐づくowned_groupの関連づけが完成すると。

class_nameオプションとは?

関連名と参照先のクラス名を異なるものにしたい場合に指定します。
以下の記事で、スッキリわかります。

https://qiita.com/wacker8818/items/eccdf0a63616feb14a70

コントローラー編集

groups_controller.rb
def create
    @group = current_user.owned_groups.new(group_params)
    @group.owner_id = current_user.id
    @group.users << current_user
    if @group.save
      redirect_to group_path(@group)
    else
      render 'index'
    end
  end

Viewでオーナー表示

index.html.erb
<%= group.user ? group.user.name : "不明" %>
  <i class="far fa-clock"><%=group.created_at.strftime('%Y/%m/%d') %>に作成</i>

<%= group.user ? group.user.name : "不明" %>
この記述も以下で紹介している記事にあった記述なのですが、
プロっぽいな・・・と思いました。
group.userが存在してたらユーザー名、
そうでないなら”不明”と表示するという記載だと思います。

以下の記事を参考にして、実装出来ました!!

うーーん難しい

正直、理解しきれていません。。。。。。
また、随時更新します。

2
4
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
2
4