Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymorphic association inserts 0 instead of raising error when column is misconfigured as Integer

Here's one that stumped me for a while, though in retrospect it should have been obvious. I was getting the error message

NoMethodError: undefined method `constantize' for 0:Fixnum

when accessing a model through a polymorphic association. Turns out the table on the belongs_to side of the association had an integer type column instead of a string.

Easily fixed, but it seems like Rails ought to raise an error in this situation -- instead it happily adds the row with 0 in the type column.

like image 739
zetetic Avatar asked Jun 07 '10 08:06

zetetic


1 Answers

This happens because parameters sent through with requests come through as strings, and therefore for integer columns that are set from params, rails calls to_i on the string to get the integer. If it can't resolve an integer from it (which happens if the string doesn't start with some digits) then to_i returns 0. This is just how ruby works. Sometimes rails will spot this and raise a warning, but it can't possibly know the name of every column that it has to check. Eg check this out (from console)

>> quiz = Quiz.first
=> <a quiz>
>> quiz.user_id = "foo"
=> "foo"
>> quiz.save
=> true
>> quiz.user_id
=> 0
like image 200
Max Williams Avatar answered Sep 28 '22 08:09

Max Williams