0
0

More than 3 years have passed since last update.

has_one型のデータを表示させたくて

Posted at

こんにちは!!
ユーザー登録が完了したら、ライブ情報を
投稿できるアプリを作成中です。
今回はhas_one型のデータの表示方法について
自分のメモ用としてアウトプットしていきたいです。

アソシエーション

作成中のアプリには3つのエンティティが存在します。
deviseを使って実装したユーザー登録をするadmin_usersテーブル、
ユーザーの詳細なプロフィールを保存するadmin_profilesテーブル、
ライブ情報を投稿できるeventsテーブルが存在します。

3つのテーブルのアソシエーションは以下の通りです。
Admin_user has_one admin_profiles.
Admin_user has_many events.
Admin_profile belongs_to admin_user.
Event belongs_to admin_user.

ユーザー登録はウィザード形式で保存する為、
AdminProfileモデルに

belongs_to :admin_user, optional: true
has_one_attached :admin_image

と記述しました。
また、ライブハウスの画像を保存したかったので、
Active Strageを利用してadmin_imageとしました。

実装したいこと

訪れたユーザーが、ライブハウスの詳細ページ(admin_users/show)にいくと
ユーザーの詳細な情報(admin_profilesテーブルに保存された情報)を
見ることができるように試みました。

admin_users_controllerには以下のように記述

class AdminUsersController < ApplicationController
  def show
    admin_user = AdminUser.find(params[:id])
    @store_name = admin_user.store_name
    @admin_profile = admin_user.admin_profile
  end
end

NoMethodError

ウキウキでブラウザを更新してみると以下の表示が。

スクリーンショット 2021-08-07 16.26.08.png

ふざけやがって。

スクリーンショット 2021-08-07 16.26.20.png

ナンジャそりゃ。
NoMethodErrorですって。

悩みすぎてrubyが嫌いになったのでやめてしまおうかと考えてました。

optional trueによる弊害

今回のエラーはウィザード形式でbelongs_toの外部キーのnilを許可する
optional: trueを記述したことで起こったようです。

ターミナルでコンソールを立ち上げて
pluckを確かめてみると

[1] pry(main)> AdminUser.pluck(:id)
   (0.3ms)  SELECT `admin_users`.`id` FROM `admin_users`
=> [5, 16, 7, 14, 12, 15, 6, 8, 13, 1, 11, 9, 4, 18, 3, 17, 2, 10]
[2] pry(main)> AdminProfile.pluck(:admin_user_id)
   (0.3ms)  SELECT `admin_profiles`.`admin_user_id` FROM `admin_profiles`
=> [4, 6, 7, 13, 14, 15, 17, 18]

admin_userとadmin_profileで紐付けられていないidが
いますねえ。

ぼっちを使う

もう今更ユーザー登録をウィザード形式で実装してたのを
やめて実装し直すとかめんどくさいんでやりたくなかったので
ボッチ演算子を使用することにしました。

<div class="profile-contents">
    <p class="shop-name"><%= @store_name %></p>
    <p class="postal-code">
      
      <%= @admin_profile&.postal_code %>
    </p>
    <p class="prefecture-text">
      <%= @admin_profile&.prefecture&.name %><%= @admin_profile&.municipality %>
    </p>
    <p class="address-text">
      <%= @admin_profile&.address %><%= @admin_profile&.building_name %>
    </p>
    <%= link_to "Google mapで見る", "#", class:"map-link" %>
    <p class="tel">
      TEL:
      <%= link_to @admin_profile&.phone_number, "#", class:"phone-number" %>
    </p>
    <p class="admin-profile">
      <%= @admin_profile&.profile %>
    </p>
  </div>

レシーバーであるオブジェクトに対してあるメソッドを実行する時にエラーを出さずにメソッドを
表示することができるぼっち演算子を使うことで解消できました。
rubyおもしろい。

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