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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With