# ActiveRecord dynamic table naming with has\_many possible?

**URL:** <https://www.ruby-forum.com/t/activerecord-dynamic-table-naming-with-has-many-possible/115462>\
**Category:** Rails\
**Created:** [September 25, 2007, 4:28pm UTC](https://www.ruby-forum.com/t/activerecord-dynamic-table-naming-with-has-many-possible/115462 "2007-09-25T16:28:42Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![jmaenpaa](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/9de053/32.png) [@jmaenpaa](https://www.ruby-forum.com/u/jmaenpaa)\
**Post date:** [September 25, 2007, 4:28pm UTC](https://www.ruby-forum.com/t/activerecord-dynamic-table-naming-with-has-many-possible/115462/1 "2007-09-25T16:28:42Z")

</div>

A legacy database I’m currently working with is setup such that each  
client (in a `clients` table) has a field containing the name of the  
associated `users` table (which is distinct for each client).

What I’d like to be able to do is take advantage of ActiveRecord’s  
has\_many (in this case :users) association, but I’m drawing a blank.

My original thinking was to either use "has\_many :users, Both  
has\_many and set\_table\_name are class methods

Is this at all possible? My original thinking was to “sneak-one-in”  
and do something like this:

class User \< ActiveRecord::Base  
belongs\_to :client  
set\_table\_name ‘#{client.users\_table}’  
end

…but set\_table\_name is a class method, plus it’s probably a chicken-  
egg thing as well.

Another way which struck me a possible was to generate a User model  
for each client dynamically, but unfortunately this is where my ruby  
skills go on holiday:

class Client  
def after\_find  
dynamic\_model = "  
class User\_#{user\_table} \< AbstractUser  
set\_table\_name ‘#{user\_table}’  
end

```
   has_many users, :class_name => User_#{user_table}
 "
 eval(dynamic_model)

```

end  
end

…again I’m caught out by the has\_many association class method.

Does anyone out there have an idea as to whether what I’m trying to  
do is at all possible? Admittedly my Ruby (and Rails for that matter)  
is incredibly rusty, buy any pointers would be great.

TIA,

John

–  
John M. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)

“Life creates itself in delirium and is undone in ennui.”

- Emile M. Cioran
