I spent some time yesterday figuring out a solution to this problem so I thought I might as well post it here.
The problem is that validations run before either record is saved, so there won’t ever be a content_id
when a new shout is being validated. The answer I came up with was to create a custom validator to check content.valid?
, like so:
class TextShout < ActiveRecord::Base
validates :body, presence: true
end
class Shout < ActiveRecord::Base
belongs_to :user, required: true
belongs_to :content, polymorphic: true, required: true, dependent: :destroy
validate :content_must_be_valid
default_scope { order(created_at: :desc) }
protected
def content_must_be_valid
if content && content.invalid?
content_errors = content.errors.full_messages.join(", ")
errors.add(:content, "not valid: #{ content_errors }")
end
end
end
Works for me. Would love to know if there’s a better way, though.