Reputation: 7339
Not sure if there is a fix for this that you know of, but when using the the globalize gem
class Menu < ActiveRecord::Base
translates :name
# other stuff ...
end
if I write an active record query as standard, it products an empty set.
-- Generically
Model.where(attribute: "Value")
doesn't work, where
Model.where('attribute = ?', 'Value')
does work.
--- A real world example from the console on my Menu model:
2.3.0 (main):0 > Menu.where(name: "Lunch Boxes")
=> []
2.3.0 (main):0 > Menu.where('name = ?', "Lunch Boxes")
=> [#<Menu:0x007fbab6dc6838 id: 12, restaurant_id: 15, name: "Lunch Boxes", created_at: Wed, 05 Jul 2017 16:07:20 EDT -04:00, updated_at: Thu, 10 Aug 2017 14:48:38 EDT -04:00>]
Can anyone tell me why this is happening?
Just for good measure
Rails 4.2.6 Ruby 2.3.0
Upvotes: 0
Views: 362
Reputation: 7339
Thanks @mu-is-too-short -- no idea how long it would have taken to figure that out on my own.
The trick to figuring out what was happening was to convert to two commands I was comparing to sql so I could see exactly what was being attempted.
Menu.where(name: "Lunch Boxes").to_sql
Menu.where('name = ?', "Lunch Boxes").to_sql
These produced, respectively:
=> "SELECT \"menus\".* FROM \"menus\" WHERE (name = 'Lunch Boxes')"
and
=> "SELECT \"menus\".* FROM \"menus\" INNER JOIN \"menu_translations\"
ON \"menu_translations\".\"menu_id\" = \"menus\".\"id\" WHERE
\"menu_translations\".\"name\" = 'Lunch Boxes' AND
\"menu_translations\".\"locale\" = 'fr'"
So then I ran the query directly in the psql console, and came back with an empty set. Because it was joining on the menu_translations table, made possible by using the model helper that comes with the Globalize gem, ie:
translates :name
SO then I checked the translation table, and found that the term "Lunch Boxes" didn't exist with any translation, and because the the attribute name
is globalized, it requires a translation.
Added the translation, problem solved. Hope this helps someone else.
Upvotes: 2
Reputation: 765
It's all right. You are trying to get this data from class, and rails waiting for filter for special characters.
More info - SQL Injection: 7.2.4 Countermeasures
Upvotes: 0