auto_complete icon indicating copy to clipboard operation
auto_complete copied to clipboard

Escaping column names

Open Tragos opened this issue 14 years ago • 2 comments

I've ran into an issue where my legacy tables use mysql reserved words (in my case, "to") as column names, and the autocomplete plugin fails to fetch the data due to a MySQL error.

To fix this, I added "quote_column_name()" calls around the "method" variables in the "auto_complete_for" method:

def auto_complete_for(object, method, options = {})
  define_method("auto_complete_for_#{object}_#{method}") do
    object_class = object.to_s.camelize.constantize
    find_options = { 
      :conditions => [ "LOWER(#{object_class.connection.quote_column_name(method)}) LIKE ?", '%' + params[object][method].downcase + '%' ],
      :order => "#{object_class.connection.quote_column_name(method)} ASC",
      :limit => 10 }.merge!(options)

    @items = object_class.find(:all, find_options)

    render :inline => "<%= auto_complete_result @items, '#{method}' %>"
  end
end

I'm not sure this is an elegant solution though.

Tragos avatar Jul 12 '10 15:07 Tragos

why not just use a ? and put the object_class.connection.call(:method) in the array...

lenary avatar Jul 12 '10 19:07 lenary

Using ? would transform it into a string, like: 'column_name' (see the difference between grave accents and single quotes), to which MySQL would treat as a literal value and not a column, as opposed to column_name. (edit: this comment system parses grave accents into code, but I hope you get the idea.)

Tragos avatar Jul 12 '10 20:07 Tragos