Rails 3.1 engines and databases

Can they have their own databases in rails 3.1 and at the same time have access to the database of the main application, for example, for user authentication How can I configure this, if possible?

thanks

+4
source share
3 answers

Yes, they can. I created engines that use a separate sqlite3 database. Thus, all engine functionality and data are isolated. Delete the engine, delete the database, and everything went without leaving a trace.

First of all, you chose to create a mounted engine . This creates a namespace and isolates the engine from the main application. This is not a requirement, but best practice. I assume what you did in the following examples.

At some point, you are going to create a model inside your engine. In the root path of the engine, enter something like this:

$ rails generate resource Post 

This will create a controller, model, and route. Everything is fine except for database migration. You are about to delete this. This migration is useless if you want to save your data separately. The only purpose of migration within the engines is to copy them to the main application database. So go ahead and get rid of it:

 $ rm -r db 

Now connect your root route and controller as usual.

There is another change made inside the model to connect to a separate database.

 module YourEngine class Post < ActiveRecord::Base establish_connection :adapter => 'sqlite3', :database => 'db/your_engine.sqlite3' end end 

Thus, the engine model will not use the main database except the one you define. The key to understanding is that the database file does not live inside the engine! This database file is located inside the host application. Since you keep everything separate, you must create this database manually. Using the sqlite3 command-line tool and the manually created create statement is faster:

 $ cd "the root dir of the host rails app" $ sqlite3 db/your_engine.sqlite3 

where do you create the table from:

 CREATE TABLE your_engine_posts (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name varchar(255) NOT NULL DEFAULT '', body text, created_at DATETIME NOT NULL, updated_at DATETIME NOT NULL); 

Presto! Now it’s just a matter of installing the engine inside your application, downloading it, and everything should be ready to roll. Obviously, now that your engine has a separate database, working with migrations is useless. You will need to update the circuit manually.

+5
source

If you are concerned about the collision of tables with the application, you can use the 'isolate_namespace' method. This is the prefix of all the names of your table with the namespace of your Engine.

Rails Casts had a good tutorial that uses this, you should check it out.

http://railscasts.com/episodes/277-mountable-engines

+1
source

Yes, they can. I wrote a guide about this http://railsforum.com/viewtopic.php?id=42143

0
source

All Articles