0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ユーザのプロフィールページ作成⑥

Posted at

プロフィールの内容を表示

app/views/profiles/show.html.haml のdisplay_nameの内容を変更していきます。

app/models/user.rb

  def display_name
    profile.nickname || self.email.split('@').first
  end

現状ニックネームが登録されていないと、エラーが起こってしまう

$Profile.first.destroy

これで、内容を削除してみます。

undefined method `nickname' for nil:NilClass
エラーが発生しました。
プロフィールは、Nilであり、Nilの中にニックネームがないので、エラーが起こってしまう。

  def display_name
    if profile && profile.nickname
      profile.nickname
    else
      self.email.split('@').first
    end

こうすることで、プロフィールがある且つプロフィールの中にニックネームがない場合は、下が実行される 

  def display_name
    profile&.nickname || self.email.split('@').first
  end

こういった短縮の形で書くこともできる👍
.&は、ぼっち演算子
prosileがnil出ない場合は、nicknameを実行する

年齢、性別を表示!

  def birthday
    profile&.birthday
  end

  def gender
    profile&.gender
  end

app/views/profiles/show.html.haml

  #{current_user.display_name} (#{current_user.birthday} • #{current_user.gender})

app/views/profiles/show.html.haml

  = current_user.profile&.introduction

追加。自己紹介を表示するように

app/models/user.rb

  delegate :birthday, :gender, to: :profile, allow_nil: true

こうすることで、

  def birthday
    profile&.birthday
  end

  def gender
    profile&.gender
  end

これを省略でき、nilの時もエラーが起こらないようにできる!

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?