LoginSignup
0
0

More than 1 year has passed since last update.

【Rails】(解決)空のデータベースに対してnil?などのメソッドで条件分岐してもエラーがでる(undefined method `〇〇◯' for nil:NilClass (NoMethodError))

Last updated at Posted at 2022-05-26

環境

  • Mac(12.2.1)
    • MacBook Pro (13-inch, 2020)
    • 2 GHz クアッドコアIntel Core i5
    • 16 GB 3733 MHz LPDDR4X
  • ruby (2.7.5)
  • rails (7.0.1)
  • mysql2 (0.5.3)

はじめに

app/controllers/contents_controller.rb
if EgoScore.where(user_id: current_user.id).last.test_result_id.nil?
  @result ="診断していません"
else
  ego_score=EgoScore.where(user_id: current_user.id).last.test_result_id
  @result = TestResult.find(ego_score).egogram_type
app/views/contents/index.html
<%=@result%>

上記でエラー

またnil?の部分をpresent?やempty?に変えてもエラー

解決した内容

app/controllers/contents_controller.rb
if EgoScore.where(user_id: current_user.id).present?
  ego_score=EgoScore.where(user_id: current_user.id).last.test_result_id
  @result = "#{TestResult.find(ego_score).egogram_type}タイプ"
else
  @result ="診断していません"
 end
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