I am developing a controller that creates a model with a polymorphic belongs_to association. What I do now to find the model it belongs to is as follows:
def find_polymorphic_model(classes)
classes_names = classes.map { |c| c.name.underscore + '_id' }
params.select { |k, v| classes_names.include?(k) }.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value)
end
end
raise InvalidPolymorphicType
end
Where classes is an array of valid types for the association.
The problem with this approach is that I have to remember in the controller which types are allowed for the model I am creating.
Is there a way to find which types are allowed for a certain polymorphic belongs_to association? Or maybe I am doing this wrong and I should not let a polymorphic controller be exposed without nesting it in the polymorphic resource (in the router)?
I also think there may be problems with the fact that Rails lazy loads classes, so to be able to find out this thing I would have to explicitly load all models at initialization time.
For your validation you don’t have to get all the possible polymorphic types. All you need is to check if the specified type (say, the value of
taggable_typeattribute) is suitable. You can do it this way:And then use:
to check whether
:taggable_typecontains a valid class.