2

I have several items that I want to lump into a single lookups table instead of having 20+ separate tables, each with the same attributes:

  • countries
  • states
  • email_types
  • phone_types
  • address_types
  • etc...

In Rails I just add the type column to the lookups table and it "magically" works.

However, I have namespaced some of the models for developer ease-of-use, as it was getting a little chaotic:

# app/models/lookup.rb
class Lookup < ActiveRecord::Base
end

# app/models/lookups/country.rb
class Lookups::Country < Lookup
end

So when I Lookups::Country.create(name: "Italy"), it stores a type of "Lookups::Country".

But as all good developers, I end up doing some refactoring, and instead of having all the lookups thrown into a single app/models/lookups namespace, I want to break them up into their various elements:

# app/models/addresses/country.rb
class Addressess::Country < Lookup
end

The sole reason to change the namespace was to re-organize the project as it grew larger and larger.

So when I Addressess::Country.create(name: "Italy") now, it stores a type of "Addressess:Country". The problem is now there are 2 "types" of countries in the lookups table.

Basically, I just "lost" my data because I moved a model to a different namespace. I would have to go and update all the "Lookups::Country" records to have a type of "Addressess::Country".

Is there any way to avoid this? I will be moving models around frequently until they are organized maturely, and cannot afford to have to do a DB update/migration every time I move a file around to make life simpler for a developer.

Dan L
  • 4,319
  • 5
  • 41
  • 74

2 Answers2

0

Overriding the sti_name class method for each model might work.

Try this -

# app/models/addresses/country.rb
class Addressess::Country < Lookup
    def self.sti_name
        "Address"
    end
end
Kaushik
  • 55
  • 6
0

This worked for me: https://gist.github.com/vamdt/75aca125883a88a9f1fd (see code)

Sabrina Leggett
  • 9,079
  • 7
  • 47
  • 50