37
43

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.

【Rails】ポリモーフィック関連の作り方と使い方

Posted at

状況設定

user has_many messages.
admin has_many messages.

user / admin に対してポリモーフィック関連を作りたい。

手順1 : rails g model

rails g model message messagable:references{polymorphic}  message:text
rake db:migrate

手順2 : modelにオプションを付加

Userモデル


class User < ActiveRecord::Base
  has_many :messages, :as => :messagable
end

Adminモデル


class Admin < ActiveRecord::Base
  has_many :messages, :as => :messagable
end

Messageモデル

※ 既に以下のbelongs_toは出来ているので、書き加える必要なし。


class Message < ActiveRecord::Base
  belongs_to :receivable, polymorphic: true
end



# 手順3 :  ポリモーフィック関連使い方


## Messageをcreateする時


```ruby

user = User.first
user.messages.create(message: "ユーザーです")

admin = Admin.first
admin.messages.create(message: "アドミンです")

結果↓

スクリーンショット 2015-11-11 21.35.18.png

Messageを取得

普通に user has_many messages. で行ける。
返ってくるのはActiveRecordRelations。

user.messages 

Kobito.0fH0Xc.png

admin.messages

Kobito.KrLFFN.png

Messagable(User or Admin)を取得

message belongs_to messagable. 少し特殊。
返ってくるのは、ActiveRecord。


message = Message.first
message.messagable 

Kobito.GTOqrM.png

後は応用可能ですね!

37
43
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
37
43

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?