Skip to content

valid? incorrectly returns true for unmapped polymorphic associations #66

@taeyang91

Description

@taeyang91

Problem:

When using polymorphic_integer_type, associating a Comment with a model that is not in the polymorphic mappings does not trigger a validation error.

For example, given this model:

class Comment < ApplicationRecord
  include PolymorphicIntegerType::Extensions

  belongs_to :commentable, polymorphic: {1 => "Post", 2 => "Photo"}
end

If a Comment is associated with a User (which is not part of the mapping), calling valid? incorrectly returns true:

> comment = Comment.new(...)
> comment.commentable = User.first
> comment.valid?
=> true

This is unexpected because User is not in the allowed mappings.

Expected Behaviour:

> comment = Comment.new(...)
> comment.commentable = User.first
> comment.valid?
=> false
> comment.errors.full_messages
=> ["Commentable must exist"]

Analysis:

The issue occurs because setting commentable to a User results in commentable_type being nil. The validation passes since this condition is not met.

It's inconsistent with the ActiveRecord's behaviour, where assigning a nil association triggers a validation error.

Proposed Fix

To align the validation logic with ActiveRecord, I suggest this:

validate do
    t = send(foreign_type)
    if t.nil?
      errors.add(foreign_type, "must exist")
    elsif !mapping.values.include?(t)
      errors.add(foreign_type, "is not included in the mapping")
    end
end

The changes ensures a nil commentable_type triggers a validation error.

Versions:

polymorphic_integer_type: 3.3.0
ruby: 3.1.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions