Ruby on Rails
JoinOnTablesWithIDAsPrimaryKey (Version #2)

I have been experiencing troubles with joins on tables when i use ‘id’ as primary key – which btw. was recommended last time I checked. The problem is that multiple columns with the name ‘id’ will appear in the result set, which causes very funny behaviour in ActiveRecord. The fix is really very simple: use SELECT <table_name>.* FROM <table_name> in stead of SELECT * FROM <table_name>.

activerecord/lib/active_record/base.rb contains the offending code in the construct_finder_sql() method. I have suplied a small diff for your convenience (should anyone know where to submit such a patch please enlighten me)…

 --- base.rb.orig        2005-10-14 17:47:37.000000000 +0200
 +++ base.rb     2005-10-14 17:48:14.000000000 +0200
 @@ -739,7 +739,7 @@
         end
 
         def construct_finder_sql(options)
 -          sql  = "SELECT * FROM #{table_name} "
 +          sql  = "SELECT #{table_name}.* FROM #{table_name} "
           sql << " #{options[:joins]} " if options[:joins]
           add_conditions!(sql, options[:conditions])
           sql << "ORDER BY #{options[:order]} " if options[:order]

I have been experiencing troubles with joins on tables when i use ‘id’ as primary key – which btw. was recommended last time I checked. The problem is that multiple columns with the name ‘id’ will appear in the result set, which causes very funny behaviour in ActiveRecord. The fix is really very simple: use SELECT <table_name>.* FROM <table_name> in stead of SELECT * FROM <table_name>.

activerecord/lib/active_record/base.rb contains the offending code in the construct_finder_sql() method. I have suplied a small diff for your convenience (should anyone know where to submit such a patch please enlighten me)…

 --- base.rb.orig        2005-10-14 17:47:37.000000000 +0200
 +++ base.rb     2005-10-14 17:48:14.000000000 +0200
 @@ -739,7 +739,7 @@
         end
 
         def construct_finder_sql(options)
 -          sql  = "SELECT * FROM #{table_name} "
 +          sql  = "SELECT #{table_name}.* FROM #{table_name} "
           sql << " #{options[:joins]} " if options[:joins]
           add_conditions!(sql, options[:conditions])
           sql << "ORDER BY #{options[:order]} " if options[:order]