Reusable State model/migration - how do you do it?

I’m new to Rails. I do a lot of work that requires standard State
FIPS codes (both alpha and numeric). I know enough on how to generate
my model and migrations and all that. It’s a rather simple model:
name:string, fipsalpha:string, fipsnum:integer. This lets me produce
dropdown lists in my app that I can tie to a FIPS code. (For example
Lousiana - LA - 22).

My question is this – is there a way to not have to populate this
data for every Rail app I use? I know you can create a constant
inside the model, but I’d like to keep this in the database). I was
wondering if there was a way to have the migration in addition to
building the schema initially populate it as well? This way I could
use this migration in any of my projects. What’s the best way to
handle something like this?

Nicholas

Never mind. I think I figured it out. You just simply have the model
created first, and in a later migration just do the
Create.activerecordclass(blah).

Nicholas

Well, you could do it all in the same migration – just after the
table is created.

Better yet, you should create a bootstrap file that you can run as a
rake task that will populate your tables.

Hope that helps.

This is what I ended up doing - although I’m not sure it’s the best
solution. It seems like I should be able to use a block statement and
iterate through a simple list to create the array.

class AddStateInfo < ActiveRecord::Migration
def self.up
State.create([
{:name => ‘Alaska’, :fipsalpha => ‘AK’, :fipsnum => ‘02’},
{:name => ‘Alabama’, :fipsalpha => ‘AL’, :fipsnum => ‘01’},
{:name => ‘Arkansas’, :fipsalpha => ‘AR’, :fipsnum => ‘05’},
… etc, etc…
])
end

def self.down
State.delete_all
end
end

On Mar 13, 6:00 pm, “[email protected]” <ESPN3.DL-

Actually I agree the better way is to model this in a fixture (csv in
this case) and then I can load it and equally use it for testing
later. Thanks for the suggestion - it’s worked out great!

Nicholas

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs