目次 閉じる
プロフィールページを作る
1対1
- ユーザーとプロフィール → 1対1
プロフィールに載せるもの
- ニックネーム(文字)
- 生年月日(日付)
- 性別(数字)
- 自己紹介(長文)
- 通知設定(Boolean)
「true」or「false」の二択から選ぶ
モデルを作る
warp(ターミナル画面)で以下を実行
rails g model Profiledb/マイグレーションファイルを開く
class CreateProfiles < ActiveRecord::Migration[6.0]
def change
create_table :profiles do |t|
# userと紐づける user_idがないとfalseになる
t.references :user, null: false
# 文字列 ニックネーム
t.string :nickname
# 長文 自己紹介
t.text :introduction
# 整数 性別は文字列じゃなくて数字にすることが多い
t.integer :gender
# 日付 生年月日
t.date :birthday
# メールの通知設定 デフォルトはfalseにしておく
t.boolean :subscribed, default: false
t.timestamps
end
end
enduser(user_id)がないと絶対に保存できません
t.references :user, null: falserails db:migrateuserとprofileを関連付ける
t.references :userによりデータベース上は紐づいたので、rails上(ActiveRecord)でも関連付けていく
ユーザーはひとり「user(単数形)」、プロフィールもひとつ「profile(単数形)」と書くこと
app/models/user.rbを開く
- 「userはprofileをひとつ持っている(
has_one)」 - 「userを消したら、profileも削除するよ(
dependent: :destroy)」
has_one :profile, dependent: :destroyapp/models/profile.rbを開く
「profileはuserに所属(belongs_to)している」
class Profile < ApplicationRecord
belongs_to :user
endconfig/routes.rbを開く
resourcesではなく、resourceを使うresourceの場合、indexが作成されない
→ profileは1つなので、showがあれば良い- さらに、
resourceの場合は:newや:createも使わない
→ :editと:updateのみ使うことが多い
Rails.application.routes.draw do
# 中略
resources :articles do
resources :comments, only: [:new, :create]
end
resource :profile, only: [:show, :edit, :update]
endapp/controllers/profiles_controller.rbを作成する
controllerでは必ず複数形「profiles」で書くこと
before_action :authenticate_user!authenticate_user → ログインしているユーザー
def show
@profile = current_user.profile
enduser.rbの中でhas_one :profileと定義しているため、.profileでプロフィールを取得できる
class User < ApplicationRecord
#中略
has_one :profile, dependent: :destroy
endapp/views/profiles/show.html.hamlを作成する
profiles_controller.rbなので、profilesのフォルダを作る
layouts/application.html.hamlにプロフィールのリンクを貼る
= link_to 'プロフィール', profile_path= link_to 'Edit', edit_profile_pathprofilesではなく、ひとつだけなのでprofileになる

| メソッド | 説明 |
|---|---|
| resources | 複数ある 例)記事・コメント |
| resource | ひとつしかない 例)プロフィール |
#DAY23

