Adding columns to DB on the fly

Hi,
I’m doing a multilanguage application which kind-of abuses the concept
of dynamic models of Rails.

I allow the application administrator to create a new language (theres
a Language model), and each time a new language is created, I
automatically add a new column that corresponds to an existing column
in the database.

for example, after creating a “Spanish” language, the code searches
the model “Products” for columns that end with _lang_en (where en is
the default language), and then creates an equivalent column with the
same type (type, constrains, and indices), which is suffixed by
_lang_es.
(then i’d dynamically show the new language text fields on the views).

Things are working perfectly in creating the new columns, however,
some weird errors happen when trying to display pages that load data
from the internationalized models, for example, “undefined method
`each_lang_column’ for #Currency:0xb67fc220”, which is a method
defined in a parent class that inherits from ActiveRecord::Base, while
the code works perfectly when I restart the application.

My question is, is there a way to reloads all application classes/
restarts the application from the code? (I’m aware of the .reload!
method, but this is not what I need, it works on the object level, and
loads the data, not the definitions).

kerdany wrote:

Hi,
I’m doing a multilanguage application which kind-of abuses the concept
of dynamic models of Rails.

I allow the application administrator to create a new language (theres
a Language model), and each time a new language is created, I
automatically add a new column that corresponds to an existing column
in the database.

for example, after creating a “Spanish” language, the code searches
the model “Products” for columns that end with _lang_en (where en is
the default language), and then creates an equivalent column with the
same type (type, constrains, and indices), which is suffixed by
_lang_es.
(then i’d dynamically show the new language text fields on the views).

This is horrible database design. I would recommend moving the
multilingual descriptions into a separate table:

Product has_many :descriptions

Description belongs_to :product, belongs_to :language

then:

products:
id: 1
price: 0.99

descriptions:
id: 1
product_id: 1
language_id: en # using ISO codes rather than numbers for this example
name: Pencil

id: 2
product_id: 1
language_id: es
name: Lápiz

and so on.

Does that make sense? If not, I’ll explain further. Clean, relational,
DRY, no reloading necessary.

Best,

Marnen Laibow-Koser
http://www.marnen.org
[email protected]