Dynamically create tables and models depending on parent.att


#1

Hi everybody!

Given those models:

###############################################################################
class Company < ActiveRecord::Base
has_many :employees

class Employee < ActiveRecord::Base
belongs_to :company

class Attribute < ActiveRecord::Base
has_many :companies, :through => :employee_attributes
has_many :employee_attributes

class EmployeeAttribute < ActiveRecord::Base
belongs_to :company
belongs_to :attribute
###############################################################################

is it possible to create a new “#{company.name.underscore}_employees”
table for each company, whose columns are given by
company.employee_attributes?

For example, with:

Company.find_by_name(“GoodCompany”).employee_attributes.collect{|e_a|
e_a.name}
=> [“name”,“position”,“salary”]

Company.find_by_name(“EvilCompany”).employee_attributes.collect{|e_a|
e_a.name}
=> [“name”,“position”,“salary”,“life_expectancy”,
“should_be_fired_at”]

,invoking Company::build_employees_tables would create two tables:

a good_company_employees table with those columns:
id, name, position, salary
and an evil_company_employees table with those columns:
id, name, position, salary, life_expectancy, should_be_fired_at

and two corresponding models:

class GoodCompanyEmployee < Employee
class EvilCompanyEmployee < Employee

Then, Company.find_by_name(“GoodCompany”).employees and
Company.find_by_name(“EvilCompany”).employees would ask two different
tables and return
GoodCompanyEmployee.find :all
and
EvilCompanyEmployee.find :all
respectively.

Is this even possible?
With my limited Rails experience, I only came up with:
-using STI and leaving life_expectancy and should_be_fired_at columns
as NULL for GoodCompanyEmployee. But in case of a lot of different
companies with a lot of different attributes, employees table would be
99% NULL.
-using serialize :attributes and method_missing to access the
attributes stored in a hash. I suppose this would be really slow and
unDRY.
-using something like magic_multi_connections…
-maybe the whole thing is defective by design, and I could come up
with the same behaviour using a completely different approach?

Any help would be greatly appreciated,
Have a good day (and thanks for the wonderful Framework),

Eric DUMINIL


#2

up?

Maybe my description was a bit too long, but I just wanted to explain
my problem right and give the reader a few more hints.

Any help would be greatly appreciated, and I promise I won’t bother
you anymore after this one!