LoginSignup
0
0

More than 1 year has passed since last update.

Railsのpolymorphicに触れる

Posted at

何をしたのか

今までpolymorphicについてなんとなくで使っていたので、理解を深める目的でpolymorphicを触れました。

今回の使用例

今回は下記の図のmodelを使います。
Comic(漫画)Novel(小説)がそれぞれAuthor(著者)という子モデルを持っているという状態です。

image.png

それぞれのモデルのコードは下記のようになっています。

author.rb
class Author < ApplicationRecord
  belongs_to :bookable, polymorphic: true
end
comic.rb
class Comic < ApplicationRecord
  has_many :authors, as: :bookable
end
novel.rb
class Novel < ApplicationRecord
  has_many :authors, as: :bookable
end

それぞれ下記のように値が入っているとします。
image.png

Authorから親モデルを取得したいときは下記のようなコードで取得できます。

Author.find(1).comic.title
Author.find(3).novel.title

# 両方ともbookableで取得できます。
Author.find(1).bookable.title
#=> ワンピース
Author.find(3).bookable.title
#=> 白夜行

ここでpolymorphicが便利なのはAuthorの親モデルがComicかNovelかを気にせずbookableで取得できるところにあると思います。

参考

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