Michiel de Mare
Michiel de Mare

Reputation: 42420

Use schema.rb in gem

I'd like rake db:schema:load to use a db/schema.rb that's not located in my app, but in one of my gems. This already works for db:seed by putting config.paths['db/seeds'] = Core::Engine.paths['db/seeds'].existent in my application.rb. (Core is a gem that's also a Rails engine).

However, there is no db/schema.rb path in config.paths and config.paths['db'] = Core::Engine.paths['db'].existent has no effect.

What's the easiest way to get this done?

Upvotes: 4

Views: 1421

Answers (5)

awilkening
awilkening

Reputation: 1062

For anyone who stumbles upon this, as of Rails 4.0 you can set the 'db' key in your engine configuration and the main app will look for your schema there.

active_record/railties/databases.rake

module MyEngine
  class Engine < ::Rails::Engine
    initializer :override_db_dir do |app|
      app.config.paths["db"] = config.paths['db'].expanded
    end
  end
end

Upvotes: 5

rovermicrover
rovermicrover

Reputation: 1453

While not totally the same thing you can do the following to have migrations in a gem act like they are part of the application. Which I have found to be a more elegant solutions for my purposes instead of trying to share schema. I hope this helps.

Migrations in Rails Engine?

Upvotes: 0

rbinsztock
rbinsztock

Reputation: 3195

why don't you use a custom rake task ?

desc 'Load a custom.rb file into the database'
  task :load_default_schema do
    file = ENV['SCHEMA'] || "path_to_your_file"
    if File.exists?(file)
      load(file)
    else
      abort %{#{file} doesn't exist yet.}
    end
  end

Upvotes: 1

DNNX
DNNX

Reputation: 6255

According to the Rails 3.2 source code https://github.com/rails/rails/blob/3-2-stable/activerecord/lib/active_record/railties/databases.rake#L400 , setting SCHEMA env variable should help:

ENV['SCHEMA'] = Core::Engine.paths['db'].existent

As I remember, the database tasks has been changed significantly in Rails 4, so this approach doesn't necessarily work in Rails 4.

Another option is to override the rake task itself in your gem.

Upvotes: 4

Sergey Sokolov
Sergey Sokolov

Reputation: 994

You can get migrations from your gem - rake gem_name:install:migrations

Upvotes: 2

Related Questions