Rails migrations for postgreSQL schemas Rails migrations for postgreSQL schemas ruby-on-rails ruby-on-rails

Rails migrations for postgreSQL schemas


I have a schema_utils library which I use and has the following method for handling migrations:

  def self.with_schema(schema_name, &block)    conn = ActiveRecord::Base.connection    old_schema_search_path = conn.schema_search_path    conn.schema_search_path = schema_name    begin      yield    ensure      conn.schema_search_path = old_schema_search_path    end  end

I then use migrations as normal so I can continue to call rake:migrateNow, in your migrations you can use:

...schemas.each do |schema|  SchemaUtils.with_schema(schema) do    #Put migration code here    #e.g. add_column :xyz, ...  endend

Because I tend to be mapping schemas to account codes I do the following:

Account.for_each do |account|  SchemaUtils.with_schema(account.code) do    #Put migration code here  endend


Check the apartment gem that's been built just for that purpose. It's brilliant.


I'm not sure if I got the question right but don't you just need to declare a few more environments in your database.yml with different "database" specified in each?