Issue
This Content is from Stack Overflow. Question asked by Dev V
I recently upgraded the rails version of my application from 6.1 to 7. After upgrading I found that sanitize_sql_array
is now changing the integer values to string.
Below are the attributes that I am passing to the method:
updates = ["`bed_count` = `bed_count` + ?", "`operating_room_count` = `operating_room_count` + ?", "`updated_at` = ?"]
values = [3.14159, 1, "2022-09-17 18:15:05"]
Now when the run the method I get the following output:
>> ActiveRecord::Base.send(:sanitize_sql_array, [updates.join(','), *values])
=> "`bed_count` = `bed_count` + '3.14159',`operating_room_count` = `operating_room_count` + '1',`updated_at` = '2022-09-17 18:33:44'"
Notice that the 3.14159 and 1 is now changed to string even though I provided integer values.
When I ran the same code in Rails 6.1, I got the following output:
"`bed_count` = `bed_count` + 3.14159,`operating_room_count` = `operating_room_count` + 1,`updated_at` = '2022-09-17 18:33:44'"
Does anybody know how can I fix this ?
Solution
seems to be related to https://github.com/rails/rails/pull/42440?
The MySQL adapter now cast numbers and booleans bind parameters to string for safety reasons.
I guess they’re working on a fix for your problem here: https://github.com/rails/rails/pull/45379
Think the best workaround right now is to cast the strings to integer/decimals in the SQL like this:
...bed_count` + CAST(? as UNSIGNED)
# or
CAST(? as DECIMAL)
This Question was asked in StackOverflow by Dev V and Answered by Adam Zapaśnik It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.