This project is archived and is in readonly mode.

#4568 ✓resolved
Hery

Reflection do not reset quoted_table name when set_table_name is invoked

Reported by Hery | May 10th, 2010 @ 01:49 PM | in 3.0.2

Hi all,

I just found this issue :

class User < ActiveRecord::Base
has_many :stats
end
class Stat < ActiveRecord::Base
  belongs_to :user
end

Somewhere in my code I have to set the table name of my Class Stat with it's id (multiple stats tables depending on user's id)

user1 = User.find 1
user2 = User.find 2

Stat.set_table_name "stats_#{user1.id}"
Stat.table_name #=> 'stats_1'
Stat.quoted_table_name #=> '`stats_1`'

user1.stats.find(:conditions => {:generated_at => Date.today})

It works fine : I can see in the log :

Stat Load (0.3ms)   SELECT * FROM `stats_1` WHERE (`stats_1`.`generated_at` = '2010-05-10') AND (`stats_1`.user_id = 1)

But when I change to stats_2 :

Stat.set_table_name "stats_#{user2.id}"
Stat.table_name #=> 'stats_2'
Stat.quoted_table_name #=> '`stats_2`'

user2.stats.find(:conditions => {:generated_at => Date.today})
Stat Load (0.0ms)   Mysql::Error: Unknown column 'stats_1.generated_at' in 'where clause': SELECT * FROM `stats_2` WHERE (`stats_1`.`generated_at` = '2010-05-10') AND (`stats_1`.user_id = 2)

After digging into active_record I think I've found it. Reflection sets an instance variable for table_name and quoted_table_name

So I added this to my initializers and all worked fine !! (Just remove the instance_variable set)

module ActiveRecord
  module Reflection
    class AssociationReflection < MacroReflection 
      def table_name
        klass.table_name
      end
      def quoted_table_name
        klass.quoted_table_name
      end
    end
  end
end

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>

Attachments

Referenced by

Pages