Rails migrations for postgreSQL schemas

假如想象 提交于 2019-12-02 17:39:21

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:migrate Now, in your migrations you can use:

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

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
  end
end

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?

I wrote pg_migrate because of these scenarios, i.e., situations in which multiple applications share the same database. There is probably a Rails way to handle this (engines?) but I too often have another app that's not Rails that needs the database too... then what?

In this case, the key feature of pg_migrate is it can generate a ruby gem; so it becomes possible to maintain your database schema separately from all the downstream applications, but all can reference it.

In your Rails Gemfile, after you've built the ruby gem using pg_migrate's 'package' command, you can do:

gem 'my_db', gem 'jam_db', :path=> "../my_db/gem_package"

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!