Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

valid? incorrectly returns true for unmapped polymorphic associations #66

Open
taeyang91 opened this issue Jan 30, 2025 · 0 comments
Open

Comments

@taeyang91
Copy link

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant