Skip to content

Commit 4c9a1e0

Browse files
Add query docs for delegated type
Lint Update activerecord/lib/active_record/delegated_type.rb Co-authored-by: Rafael Mendonça França <[email protected]>
1 parent 0f9aaa5 commit 4c9a1e0

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

activerecord/lib/active_record/delegated_type.rb

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,26 @@ module ActiveRecord
113113
# end
114114
# end
115115
#
116+
# == Querying across records
117+
#
118+
# A consequence of delegated types is that querying attributes spread across multiple classes becomes slightly more
119+
# tricky, but not impossible.
120+
#
121+
# The simplest method is to join the "superclass" to the "subclass" and apply the query parameters (i.e. <tt>#where</tt>)
122+
# in appropriate places:
123+
#
124+
# Comment.joins(:entry).where(comments: { content: 'Hello!' }, entry: { creator: Current.user } )
125+
#
126+
# For convenience, add a scope on the concern. Now all classes that implement the concern will automatically include
127+
# the method:
128+
#
129+
# # app/models/concerns/entryable.rb
130+
# scope :with_entry, ->(attrs) { joins(:entry).where(entry: attrs) }
131+
#
132+
# Now the query can be shortened significantly:
133+
#
134+
# Comment.where(content: 'Hello!').with_entry(creator: Current.user)
135+
#
116136
# == Adding further delegation
117137
#
118138
# The delegated type shouldn't just answer the question of what the underlying class is called. In fact, that's

0 commit comments

Comments
 (0)