This is a very quick recipe for using a backend process with a Rails frontend. I’ve been experimenting with Rails at work and needed a long running backend process to keep the information displayed in the frontend up to date and to do house-keeping tasks.
I wanted to share models and helper code between the back and frontends, so required the ability to use Active Record outside the typical Rails environment. It turns out this is simple to do. I couldn’t find an example on the web on how to set this up, so I decided to write one.
I assume a familiarity with both Ruby and Rails, and will go through the steps to create a simple application. The application consists of backend which posts messages into a MySql database along with a frontend to display the messages in the database.
This tutorial uses the newly released Rails 2.0, but the steps needed for 1.x are identical (I initially used 1.x). Some of the code is slightly different in 2.0, so you may need to adapt the code shown a little.
A word of caution: I haven’t looked here at coping with concurrent database accesses from the front- and back-ends. I’ve no idea how ActiveRecord handles database locking when explicit transactions are not used, so my approach may break down under load. It certainly works for how I am using it, however.
First create a new Rails site:
As the fronted is drop-dead simple, a scaffold model/view/controller should be fine:
Create the database “backend_demo_development” in MySql (or whichever database you are using). I used CocoaMySql to do this.
The database migration needs to be updated to add a message field to the database. This code uses Rails 2.0 features to simplify setup. Open
db/migrate/001_create_messages.rb and add the message field.
class CreateMessages < ActiveRecord::Migration def self.up create_table :messages do |t| t.string :message, :null => false t.timestamps end end Next run the migration to create the database tables. The scaffolds created by Rails 2 are not so functional as in 1, so edit `app/views/messages/index.html.erb`. Add the following line into the table row generating code: Similarly, edit `app/views/messages/new.html.erb` to add a field for the message text into the form: Now, the Rails site is complete, so run the server: Open http://localhost:3000/messages in your browser and check there are no errors, and all you can see is an empty list. Use the “New Message” link to create a new message and make sure it appears in the /messages list. Hit control-c in the console to kill the server. Now the backend needs to be written. #### Creating the Backend To keep things simple, the backend is going to be stored in backend_demo/backend. Create this folder. Create backend/backend.rb and open it in your editor, entering the following code:
- These are the requires for using active record and loading
- the settings from your rails configuration