AR삽질러

Rails 一日一つメソッド (Day18) Associations 본문

Ruby/RubyOnRails-日本語

Rails 一日一つメソッド (Day18) Associations

아랑팡팡 2024. 1. 9. 23:03
728x90

 

Rails 一日一つメソッド (Day18) Associationsメソッド

アソシエーションとは

 - Associationsとは、Table同士の関連付け(リレーションシップ )をモデル上の関係として操作できるようにする仕組み。

 

usersTable
id name email
1 tistory tistory@examaple.com
2 ex ex@example.com
3 hana hana@example.com

 

boardsTable
id user_id title content
1 1 title1 content1
2 1 title2 content2
3 1 title3 content3

 

一般的に1人のユーザーが複数の投稿を作成できる。テーブル同士の関連付けでアソシエーションで、user : 1が作成したboardが取得できる。

@user = User.find(1)
@posts = Post.where(user_id: @product.id)

 

# user.rb
class User < ApplicationController
	has_many :posts
end

# posts.rb
class Post < ApplicationController
	belongs_tp :user
end

Userモデル

 - Userモデルは複数の Postを持つ事ができる。これを表すために has_manyメソッドを使う。

Postモデル

 - 各Postは特定の Userに属し、これを表すために belongs_toメソッドを使う。

 

@user = User.find(1)
@posts = Post.where(user_id :@user.id)

@user = User.find(1)で usersテーブルからIDが1のユーザーを探し、@user変数に割り当てる。

@posts = Post.where(user_id :@user.id) で postsテーブルで user_idが @user.idのboardを読み出す。

 

アソシエーション定義し、テーブル同士の関連付けをモデル同士の関係として操作できるようになる。


リレーションシップとは

 - テーブル同士の関連付けのことで、ユーザーが複数の投稿をCRUDする必要がある。

 

主キー(Primary Key )

 - 主キーはテーブル中の角レコードを識別することに使われる。

 - 例)id : 各ユーザーの一意性を持っているカラム

 

外来キー(Foreign Key)

 - 他のテーブルのレコードを参照するカラム - 例)user_id : userテーブルの idカラムを参照し、特定の投稿がどんなユーザーによって作成されたか識別する。

Users Table
| id | name   | email                |
|----|--------|----------------------|
| 1  | Alice  | alice@example.com    |
| 2  | Bob    | bob@example.com      |
| 3  | Carol  | carol@example.com    |

Boards Table
| id | user_id | title  | content   |
|----|---------|--------|-----------|
| 1  | 1       | Title1 | Content1  |
| 2  | 1       | Title2 | Content2  |
| 3  | 2       | Title3 | Content3  |

 


アソシエーションの種類

  • belogns_to
  • has_one
  • has_many
  • has_many :through
  • has_and_belongs_to_many (HABTM)
  • belogns_to :polymorphic
  • has_one :through

 

728x90
반응형
LIST