用于PostgreSQL模式的Rails迁移 [英] Rails migrations for postgreSQL schemas
问题描述
我正在使用针对不同客户端的PostgreSQL模式的多租户Rails应用程序. Rails迁移不能立即使用多个模式,因此我做了以下rake任务来迁移所有模式,它似乎可以工作.我的问题是其他人是否实施了更好,更优雅的解决方案.我也很高兴有一个很好的教程,其中包括使用多种模式的PostgreSQL的Rails代码示例.到目前为止,我只找到了关于此主题的很好的演示
I'm working on a multi-tenant rails application using PostgreSQL schemas for different clients. Rails migrations don't work with multiple schemas out of the box, so I made the following rake task to migrate all schemas and it seems to work. My question is if others have implemented better and more elegant solutions. I would also be really happy with a good tutorial including rails code examples for PostgreSQL using multiple schemas. So far I have only found a good presentation on the subject http://aac2009.confreaks.com/06-feb-2009-14-30-writing-multi-tenant-applications-in-rails-guy-naor.html and an example of what I'm aiming for tomayko.com/writings/rails-multiple-connections
desc 'Migrates all postgres schemas'
task :schemas do
# get all schemas
env = "#{RAILS_ENV}"
config = YAML::load(File.open('config/database.yml'))
ActiveRecord::Base.establish_connection(config[env])
schemas = ActiveRecord::Base.connection.select_values("select * from pg_namespace where nspname != 'information_schema' AND nspname NOT LIKE 'pg%'")
puts "Migrate schemas: #{schemas.inspect}"
# migrate each schema
schemas.each do |schema|
puts "Migrate schema: #{schema}"
config = YAML::load(File.open('config/database.yml'))
config[env]["schema_search_path"] = schema
ActiveRecord::Base.establish_connection(config[env])
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Migrator.migrate('db/migrate', ENV["VERSION"] ? ENV["VERSION"].to_i : nil)
end
end
推荐答案
我有一个schema_utils库,可以使用它,并且具有以下方法来处理迁移:
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
然后我像往常一样使用迁移,因此我可以继续调用rake:migrate 现在,在迁移中,您可以使用:
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
这篇关于用于PostgreSQL模式的Rails迁移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!