LoginSignup
0
0

More than 1 year has passed since last update.

【Ruby on Rails】関連付けされたモデルデータの取得について

Posted at

はじめに

Railsなどを中心に勉強中のエンジニア初心者が他の記事を参考にしたり、実際に実装してみたりして、アウトプットの一環としてまとめたものです。
間違っていることもあると思われるので、その際は指摘いただけると幸いです。

モデルのリレーション

既に、Reservationモデル、Roomモデル、Userモデルに下記のような関係性がある前提とする。

  • Userレコードは複数のRoomレコード、Reservationレコードに紐づく(複数の部屋を登録でき、複数の予約もできる)。
  • Reservationは1つのUserレコード、1つのRoomレコードにのみ紐づく。
  • Roomは1つのUserレコードに紐づく一方で、複数のReservationレコードに紐づく。
# user.rb
class User < ApplicationRecord
  has_many :rooms
  has_many :reservations
end

# reservation.rb
class Reservation < ApplicationRecord
  belongs_to :user
  belongs_to :room
end

# room.rb
class Room < ApplicationRecord
  belongs_to :user
  has_many :reservation
end

リレーションを用いたデータの取得

上記のようなリレーションが定義されている場合は、例えば、以下のようにしてデータを取得することができる。

reservationレコードに紐づいているroomの名前(name)を取得したい場合

以下のようにreservationから関連づいているroomの属性まで取得することができる。

@reservation.room.name

リレーションを活用したデータ取得の例

<table>
	<tr>
	  <th>ルーム名</th>
	  <th>ルーム紹介</th>
	  <th class='th-introduction'>宿泊人数</th>
	</tr>
	
	<% @reservations.each do |reservation| %>
	  <tr>
	    <td><%= reservation.room.room_name %></td>
	    <td><%= reservation.room.room_introduction %></td>
	    <td><%= reservation.number_of_people %></td>
	  </tr>
	<% end %>
</table>

最後に

いかがでしたでしょうか。
ここ違うよ!でしたり、こうした方がいいよ!などがあればコメントいただけると幸いです。

他にも下記のような記事を投稿しております。
興味がありましたら、ぜひご覧ください。

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