Patching acts-as-taggable-on: column reference “context” is ambiguous

October 26, 2009

Certain errors in Rails send a shiver down the spine because they deal with generated SQL which can be such a dreadful problem to fix. Today I got the shivers from acts-as-taggable-on and the following error message:

PGError: ERROR: column reference "context" is ambiguous

The source of the problem is the plugin’s dynamic tag contexts and proper table aliasing when (at least in my case) trying to combine multiple “context” conditions in a single query. Fortunately, the solution is easy enough and can be traced back to the find_options_for_tagged_with method.

Below you can see where the context clause doesn’t get a proper alias:

def find_options_for_find_tagged_with(tags, options = {})
   . . .
    unless (on = options.delete(:on)).nil?
      conditions << sanitize_sql(["context = ?",on.to_s])
    end
    taggings_alias, tags_alias = "#{table_name}_taggings", "#{table_name}_tags"
   . . .
end

The solution is simple:

def find_options_for_find_tagged_with(tags, options = {})
   . . .
    taggings_alias, tags_alias = "#{table_name}_taggings", "#{table_name}_tags"
    unless (on = options.delete(:on)).nil?
      conditions << sanitize_sql(["#{taggings_alias}.context = ?",on.to_s])
   end
   . . .
end

Tags: ,

Leave a Reply

Powered by WP Hashcash