Rails delegated_type
Rails 6.1 added delegated_type for the ones who like polymorphic relations. So in addition to set a regular polymorphic relation in rails you can also call delegated_type
method to inject a bunch of useful methods and scopes for you. Check this out:
class Content < ApplicationRecord
# belongs_to :contentable, polymorphic: true
delegated_type :contentable, types: %w[ TilPost BlogPost ]
end
class TilPost < ApplicationRecord
has_one :content, as: :contentable
end
class BlogPost < ApplicationRecord
has_one :content, as: :contentable
end
And this will produce helper methods like:
content.contentable_class
# => +TilPost+ or +BlogPost+
content.contentable_name
# => "til_post" or "blog_post"
Content.til_posts
# => Content.where(contentable_type: "TilPost")
content.til_post?
# => true when contentable_type == "TilPost"
content.til_post
# => returns the til_post record, when contentable_type == "TilPost", otherwise nil
content.til_post_id
# => returns contentable_id, when contentable_type == "TilPost", otherwise nil
Tweet