This project is archived and is in readonly mode.
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
-
Tanel Suurhans April 30th, 2010 @ 10:17 AM
- Tag set to associations, belongs_to_polymorphic_association
-
Tanel Suurhans April 30th, 2010 @ 11:34 AM
Added a patch for current master (this issue seems to exist in rails 3 also).
-
Santiago Pastorino February 2nd, 2011 @ 04:43 PM
- State changed from new to open
This issue has been automatically marked as stale because it has not been commented on for at least three months.
The resources of the Rails core team are limited, and so we are asking for your help. If you can still reproduce this error on the 3-0-stable branch or on master, please reply with all of the information you have about it and add "[state:open]" to your comment. This will reopen the ticket for review. Likewise, if you feel that this is a very important feature for Rails to include, please reply with your explanation so we can consider it.
Thank you for all your contributions, and we hope you will understand this step to focus our efforts where they are most helpful.
-
Santiago Pastorino February 2nd, 2011 @ 04:43 PM
- State changed from open to stale
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>