本日の学習内容
group機能の実装
実装にあたり下記の順番で実装してきます。
コントローラとモデルを作成する
まず、前提として以前に作成したデータベースの設計書を元に構成を確認します。
## groupsテーブル
|Column|Type|Options|
|------|----|-------|
|name|string|null: false|
### Association
- has_many :users, through: :groups_users
- has_many :groups_users
- has_many :messages
create_table :groups do |t|
t.string :name, null: false
t.index :name, unique: true
t.timestamps
end
t.indexに関しては、index(column_name, options = {})で定義できるらしい。
見たことのない形だったので、こちらを参照にしました。
次いで、
## groups_usersテーブル
|Column|Type|Options|
|------|----|-------|
|user_id|integer|null: false, foreign_key: true|
|group_id|integer|null: false, foreign_key: true|
### Association
- belongs_to :group
- belongs_to :user
create_table :group_users do |t|
t.references :group, foreign_key: true
t.references :user, foreign_key: true
t.timestamps
end
それぞれのテーブルに関しては上記のようにマイグレーションファイルに追記して実装していきます。
reference型を使う場合の外部キー制約のついたカラムを作成するときにメリットがあります。
#通常の記述だと下記のようになる
create_table :group_users do |t|
t.string :user
end
add_foreign_key :group_users, :users
reference型を使用しない場合には、foreign_keyが使用できない点に注意する必要がある。また、reference型を使用していてもforeign_keyを使用していないと外部キー設定は出来ないのでこちらも注意です。
そして、設定後に下記を実行します。
してできたmigrationファイルの方にアソシエーションの記述を行なっていきます。
こちらに関しては、validateの設定も忘れずに行うようにします。
ルーティングを設定する
#変更前
Rails.application.routes.draw do
devise_for :users
get 'messages' => 'messages#index'
resources :users, only: [:edit, :update]
root :to => "messages#index"
end
#変更後
Rails.application.routes.draw do
devise_for :users
root 'messages#index'
resources :users, only: [:index, :edit, :update]
resources :groups, only: [:new, :create, :edit, :update] do
resources :messages, only: [:index, :create]
end
end
routingが変更前が色々とごちゃごちゃしていたことに気づかなかったので見直しをしていきます。
変更後に関してroutingをネストしていますが、ネスト有無の違いで下記のような違いが生まれます。
ネスト有
group_messages GET /groups/:group_id/messages(.:format) messages#index
POST /groups/:group_id/messages(.:format) messages#create
ネスト無
messages GET /messages(.:format) messages#index
POST /messages(.:format) messages#create
あとは該当するアクションをコントローラに定義して、ビューを作成して割り当てます。
このあとで実際に機能を実施していくのでまた別途分けて記述していきます。
今日の英単語
●validate 検証
意味分かるまでなんだろうと思ってたけど分かったらオブジェクトを保存する前に検証するっていう簡単なこととして理解できた。
本日の学習内容は以上になります。
お読みいただきありがとうございます。
参照:https://qiita.com/ryouzi/items/2682e7e8a86fd2b1ae47
:https://api.rubyonrails.org/v5.1.7/classes/ActiveRecord/ConnectionAdapters/Table.html
:https://dev.mysql.com/doc/refman/5.6/ja/char.html
:https://railsguides.jp/active_record_validations.html