method
delegated_type
Ruby on Rails latest stable (v6.1.7.7)
-
0 notes -
Class: DelegatedType
- 1.0.0
- 1.1.6
- 1.2.6
- 2.0.3
- 2.1.0
- 2.2.1
- 2.3.8
- 3.0.0
- 3.0.9
- 3.1.0
- 3.2.1
- 3.2.8
- 3.2.13
- 4.0.2
- 4.1.8
- 4.2.1
- 4.2.7
- 4.2.9
- 5.0.0.1
- 5.1.7
- 5.2.3
- 6.0.0
- 6.1.3.1 (0)
- 6.1.7.7 (0)
- 7.0.0 (38)
- 7.1.3.2 (13)
- What's this?
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?