【Ruby on Rails】Delegated Type
Delegated Type
Rails: ActiveRecord::DelegatedType APIドキュメント(翻訳)
複数モデルのオブジェクト、複数テーブルのレコードを統一的に扱いたいケースがあります。たとえば、コメントモデルとメッセージモデルのレコード群を足し合わせたものから最新レコード3つを取得したいようなケースです。
Delegated Typeでは、個々のモデルは一般のモデルと同じくそれぞれのテーブルを持ち、共通部分を統一的に管理するモデルとそのテーブルを別途導入します。このような構成にすると、個々のモデルで必要になったカラムはそれぞれのモデルへ加えれば良く、共通で必要なカラムは共通部分を管理するモデルへ追加することができます。
スーパークラスにdelegated_type メソッドでDelegatedTypeである旨を示す。
:types オプションには委譲先クラス群の名前を書く。
code:ruby
# Schema: entries id, account_id, creator_id, created_at, updated_at, entryable_type, entryable_id
class Entry < ApplicationRecord
belongs_to :account
belongs_to :creator
delegated_type :entryable, types: %w Message Comment
end
module Entryable
extend ActiveSupport::Concern
included do
has_one :entry, as: :entryable, touch: true
end
end
# Schema: messages id, subject, body
class Message < ApplicationRecord
include Entryable
end
# Schema: comments id, content
class Comment < ApplicationRecord
include Entryable
end
#rails