Consider this link: ActiveRecord::DelegatedType
Here is the standard example - but note that Comments require the presence of content
- without which validation should fail:
# 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
validates_presence_of :content
end
Now if I tried to create a comment without any content - this seems to work perfectly fine!
Entry.create entryable: Comment.new(), creator: Current.user
# works fine!
I would expect validation to fail. Was wondering how you all manage validation when you are using delegated types. Probably, different types might have different validation rules.
Any pointers would be much appreciated.