問題一覧に戻る
上級高度なデータベース
問題59: ポリモーフィック関連
Railsでポリモーフィック関連を実装する方法を学習します。これにより、一つのモデルが単一の関連付けを使用して複数の他のモデルに属することができます。この強力なパターンは、異なるタイプのコンテンツに添付できるコメント、タグ、いいねなどの機能で一般的に使用されます。
# Comment model
class Comment < ApplicationRecord
# ポリモーフィックbelongs_toを定義
belongs_to :, polymorphic:
end
# ポリモーフィックカラムを追加
t.references :commentable, : true
# 親モデルの関連付け
class Post < ApplicationRecord
has_many :comments, : :commentable
end
# ポリモーフィック親にアクセス
comment = Comment.first
comment. # Returns Post or Product instance