プロフィールの内容を表示
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の時もエラーが起こらないようにできる!