Search code examples
ruby-on-railsrubyactiverecordrails-activerecordarel

How do I escape a MySql reserved name in ActiveRecord Relations?


I'm working with an older (rails 4) code base and I've been tasked with updating the mysql2 gem to support the latest db version. With our current version of the gem and code, everything works fine, but when upgrading I'm running into a naming conflict with the reserved word, 'groups'.

I've managed to escape it with backticks in all but one query. We call <modelname>.send(name, args), and when name is :groups, we get an error. The send returns an active record relation. The relation.to_sql shows me it's all escaped but for one thing, the final groups which appears to be tacked onto the end of a select * from a union of selects:

SELECT `groups`.* 
  FROM 
( 
   (SELECT `groups`.* 
      FROM `groups` 
      WHERE ...) 
   UNION ALL 
   (SELECT `groups`.* 
      FROM `groups` 
      WHERE ...) 
) groups

I've been trying to find a way to escape that last groups reference. The only way I can think of is to just turn this into Arel sql and run the query that way. Is there some kind of 'name' I can pass to the ActiveReccord relation so it gives me an escaped groups?

Thank you so much for helping!


Solution

  • I go for out of the box solutions:

    • Rename the table. If yours is the only application then this would be ideal.
    • Make a view of the table and use that. If you have other applications using the table then this might be the way to go. Make a view of it and do all rails access through the view. You get to have your cake and eat it. It just adds a little complexity that you could avoid by simply renaming the table.