Skip to content

order field is not wrapped in backquotes #73

@balbesina

Description

@balbesina

My table has index field.

# model
class MenuItem < ApplicationRecord
  acts_as_tree order: :index
end
# console
>> MenuItem.roots
 MenuItem Load (0.3ms)  SELECT  `menu_items`.* FROM `menu_items` WHERE `menu_items`.`parent_id` IS NULL ORDER BY index
Traceback (most recent call last):
ActiveRecord::StatementInvalid (Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'index' at line 1: SELECT  `menu_items`.* FROM `menu_items` WHERE `menu_items`.`parent_id` IS NULL ORDER BY index)

Solution is to backquote order field:

acts_as_tree order: "`index`"
# or
acts_as_tree order: "`#{table_name}`.`index`"

When I use that field manually it is correctly wrapped by rails:

scope :root_items, -> { where(parent: nil).order(:index) }
# resulting sql
SELECT  `menu_items`.* FROM `menu_items` WHERE `menu_items`.`parent_id` IS NULL ORDER BY `menu_items`.`index` ASC

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions