This project is archived and is in readonly mode.

#4503 ✓stale
Tanel Suurhans

Polymorphic belongs_to with blank values causes unwanted behavior

Reported by Tanel Suurhans | April 29th, 2010 @ 10:44 PM

Found two cases where assigning a blank value (an empty string) to a polymorphic belongs_to causes unexpected behavior in rails 2.3.5.

class User < ActiveRecord::Base
  belongs_to :pony, :polymorphic => true
end

user = User.new
user.pony = "" # => exception thrown

This assignment throws an exception because the empty string does not get caught into this check in belongs_to_polymorphic_association.rb

def replace(record)
  if record.nil?
  end
end

With ruby 1.8.7 it passes through the record_id(record) method, returning the object_id and then blowing up with "undefined method base_class' for String:Class". With ruby 1.9.1 it doesn't even get that far, ending in "undefined method 'id' for "":String".

The other case when things go wrong happens like this:

user = User.new
user.pony_id = ""
user.pony_type = ""
user.save
user.pony # => exception thrown

This throws NoMethodError: undefined method 'find' for Object:Class, happening due to the empty string not getting caught in this condition in belongs_to_polymorphic_association.rb

def association_class
  @owner[@reflection.options[:foreign_type]] ? @owner[@reflection.options[:foreign_type]].constantize : nil
end

This method tries to do "".constantize which results in Object and afterwards Object,find is called, which is invalid.

I have attached failing tests and a patch fixing this behavior for rails 2.3.5

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>

People watching this ticket

Pages