Flowdock
method

delegated_type

Importance_2
Ruby on Rails latest stable (v6.1.7.7) - 0 notes - Class: DelegatedType
delegated_type(role, types:, **options) public

Defines this as a class that’ll delegate its type for the passed role to the class references in types. That’ll create a polymorphic belongs_to relationship to that role, and it’ll add all the delegated type convenience methods:

class Entry < ApplicationRecord
  delegated_type :entryable, types: %w[ Message Comment ], dependent: :destroy
end

Entry#entryable_class # => +Message+ or +Comment+
Entry#entryable_name  # => "message" or "comment"
Entry.messages        # => Entry.where(entryable_type: "Message")
Entry#message?        # => true when entryable_type == "Message"
Entry#message         # => returns the message record, when entryable_type == "Message", otherwise nil
Entry#message_id      # => returns entryable_id, when entryable_type == "Message", otherwise nil
Entry.comments        # => Entry.where(entryable_type: "Comment")
Entry#comment?        # => true when entryable_type == "Comment"
Entry#comment         # => returns the comment record, when entryable_type == "Comment", otherwise nil
Entry#comment_id      # => returns entryable_id, when entryable_type == "Comment", otherwise nil

The options are passed directly to the belongs_to call, so this is where you declare dependent etc.

You can also declare namespaced types:

class Entry < ApplicationRecord
  delegated_type :entryable, types: %w[ Message Comment Access::NoticeMessage ], dependent: :destroy
end

Entry.access_notice_messages
entry.access_notice_message
entry.access_notice_message?
Show source
Register or log in to add new notes.