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 inste开发者_开发百科ad 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
In my case the modeltable_type
was was not a string type
fixing this solve my problem.
精彩评论