rails/rails — Issue #3584: Rails 3.1 PostgreSQL seeding schema
Author: chrismhilton
Created: 2011-11-09 15:24:41+00:00
State: open

I have a Rails 3.1 multi-tenant app using PostgreSQL which creates a schema for each customer. A rake task is initially used to create the database including the creation & migration of a "template" schema and the application config schema_search_path is set to "\"$user\",public,template".

When creating a customer the helper methods shown below are used to create, load and seed the schema (using standard db schema & seeds files).

Since moving from 3.0.10 to 3.1.1 if I create two customers, one after the other, the second customer schema is loaded with tables, however, the seed data is added to the first customer's schema.

Stranger still is that my seeds file will only attempt to create records if the table is empty (as shown in the example below) - it would appear that the :count method is using the correct search_path while the :save method is using the search_path for the first customer's schema.

Schema helper methods:

```
def self.create_and_load_schema(schema_name, schema_file, seeds_file)
conn = ActiveRecord::Base.connection
conn.execute "create schema #{schema_name.inspect}"

with_schema(schema_name) do
load(schema_file)
end

with_schema(schema_name) do
load(seeds_file)
end
end

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.inspect},"\"$user\",public"
begin
yield
ensure
conn.schema_search_path = old_schema_search_path
end
end
```

Seeds file example:

```
if SystemSetting.count == 0

setting = SystemSetting.new(:name => "locale", :value => :en)
setting.save!

end
```