8
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ポリモーフィックを実装する

Last updated at Posted at 2015-05-10

ポリモーフィックの実装の説明しているサイトは色々あるけれどrails g modelコマンドを使って説明しているサイトがないのでメモ

モデルを作成する

子モデルを作成

$ rails g model children_one children_one_name:string
$ rails g model children_two children_two_name:string

親モデルを作成

$ rails g model parent parentable:references{polymorphic}:index name:string

generate

$ rake db:migrate

リレーションを作成

# 子クラス
class ChildrenOne < ActiveRecord::Base
  # 追加
  has_many :parents, :as => :parentable
end

# 子クラス
class ChildrenOne < ActiveRecord::Base
  # 追加
  has_many :parents, :as => :parentable
end
 
# 親クラス
class Parent < ActiveRecord::Base
  belongs_to :parentable, polymorphic: true
end

親クラスから子クラスを参照

# 親クラスに紐づく子クラスChildrenOneかChildrenTwoが参照される
Parent.first.parentable
8
9
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
8
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?