Reputation: 658
Is it possible to append two databases in rails application? For example, SQLite database is portable. I can download SQLite database from another server. When rails application starts, it mount the database. Can i append all the data from another database to existing database? May be SQLite provide a way for merging databases?
Upvotes: 1
Views: 226
Reputation: 25270
If you want to "seed" your database with data from an external source, like a central location, your best bet is to:
I do something like this on some projects. I would not, however, perform the merge automatically: I'd rather use the db/seeds.rb
file and the rake db:seed
task:
if State.count == 0
State.transaction do
CSV.foreach("#{::Rails.root}/db/seed_data/states.csv", 'r') do |row|
code, acronym, name = *row
State.create! code: code, acronym: acronym, nane: name
end
end
end
In this code I load the data from a local file, but you can easily change to a remote file using Net::HTTP
.
Upvotes: 1
Reputation: 4394
I'm not sure sure what did you mean saying "append databases in application". But you can use 2 different (with different schemes) databases in your application. For example:
config/database.yml
development:
adapter: mysql2
encoding: utf8
reconnect: false
database: project_dev
pool: 5
username: project
password:
test:
adapter: mysql2
encoding: utf8
reconnect: false
database: project_test
pool: 5
username: project
password:
sqlite:
development:
adapter: sqlite3
database: db/development.project.db
pool: 5
timeout: 5000
test:
adapter: sqlite3
database: db/test.project.db
pool: 5
timeout: 5000
Models:
Abstract model for all sqlite models; uses connection ninja gem
class SqliteModel < ActiveRecord::Base
self.abstract_class = true
use_connection_ninja(:sqlite)
end
Sqlite model
class Book < SqliteModel
set_table_name :Books
set_primary_key :BookID
belongs_to :volume, :foreign_key => :VolumeID
has_many :chapters, :foreign_key => :BookID
end
Mysql model
class Highlight < ActiveRecord::Base
# ...
end
You can even use associations between tables in different databases.
But if you was asking about using 2 databases with the same scheme(i.e. just different data), then my answer is no, it's not possible(I can be wrong though). I think that is a question about replication, synchronization, backups or something similar - DB layer, not application.
Of course you can have 2 same tables in both databases, 2 models - one per database, and then just copy records from one to another. But Rails won't do it automatically.
Upvotes: 2