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

Added option to validate which models are allowed to be associated to a polymorphic belongs_to #51738

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 10 additions & 0 deletions activerecord/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
* Added option to validate which models are allowed to be associated to a polymorphic `belongs_to`.

Ex:
```ruby
belongs_to :commentable, polymorphic: ["Post", "Comment"]
```
This automatically adds an inclusion validator to commentable_type, to ensure that it's either Post or Comment.

*Nate Matykiewicz*

* Improve `ActiveRecord::Store` to raise a descriptive exception if the column is not either
structured (e.g., PostgreSQL +hstore+/+json+, or MySQL +json+) or declared serializable via
`ActiveRecord.store`.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,12 @@ def self.define_validations(model, reflection)
required = !reflection.options[:optional]
end

if reflection.options[:polymorphic].is_a?(Array)
model.validates reflection.foreign_type,
inclusion: { in: reflection.options[:polymorphic].map { |klass| klass.to_s.freeze } },
if: ->(record) { record.read_attribute(reflection.foreign_type) }
end

super

if required
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1374,6 +1374,28 @@ def test_polymorphic_counter_cache
end
end

class TestPolymorphicArrayAllowed < ActiveRecord::Base
self.table_name = "wheels"
belongs_to :wheelable, polymorphic: ["Book", :Essay], optional: false
end

def test_polymorphic_with_allowed_class_string_array
wheel = TestPolymorphicArrayAllowed.new

assert_not_predicate wheel, :valid?
assert_equal ["Wheelable must exist"], wheel.errors.full_messages

wheel.wheelable = Book.create!
assert_predicate wheel, :valid?

wheel.wheelable = Essay.create!
assert_predicate wheel, :valid?

wheel.wheelable = Citation.create!
assert_not_predicate wheel, :valid?
assert_equal ["Wheelable type is not included in the list"], wheel.errors.full_messages
end

def test_polymorphic_with_custom_foreign_type
sponsor = sponsors(:moustache_club_sponsor_for_groucho)
groucho = members(:groucho)
Expand Down
10 changes: 10 additions & 0 deletions guides/source/association_basics.md
Original file line number Diff line number Diff line change
Expand Up @@ -538,6 +538,16 @@ class CreatePictures < ActiveRecord::Migration[7.2]
end
```

In this example, `imageable` can have any model assigned to it. If you wanted to ensure that the `imageable_type` is only `Employee` or `Product`, you can set the `polymorphic` option to an array of allowed class names. This will [add an inclusion validator][inclusion validator] to the `imageable_type` column, which adds a validation error if `imageable` is not one of the expected classes:

[inclusion validator]: active_record_validations.html#inclusion

```ruby
class Picture < ApplicationRecord
belongs_to :imageable, polymorphic: ["Employee", "Product"]
end
```

NOTE: Since polymorphic associations rely on storing class names in the
database, that data must remain synchronized with the class name used by the
Ruby code. When renaming a class, make sure to update the data in the
Expand Down