|
Connecting to External Databases
By: Bruce Bahlmann - Contributing Author (your
feedback
is important to us!)
In rails development, when creating web forms, you often want to work with
or display data contained on an external database. External being a database
which is located on a physically separate host from the one the rails
program is currently executing on.
The simplest way
to configure your rails application to access a remote database involves the
following configurations.
[config/database.yml]
exdatabase:
adapter: mysql2
database: nameOfDatabase
username: username
password: password
host: hostnameofdatabase
First step is add some lines to the [config/database.yml] file. Here you
name the database connection [exdatabase], assign an adapter [mysql2], name
the database which you are connecting [nameofDatabase] as well as the
username, password, and host [hostnameofdatabase] associated with accessing
that database. Note: The username and password must be setup in the
database's user administration and allowed external access.
[app/models/employee.rb]
class Employee < ActiveRecord::Base
establish_connection :exdatabase
set_table_name databaseTable
set_primary_key keyofTable
set_inheritance_column :ruby_type
end
Second create a file in the models [app/models] named appropriately. In this case, [employee.rb]
and then within this file a class called Employee was entered. Next enter
information about the external database you are associating with this model.
For example, which external database connection are you using [exdatabase],
specific table [databaseTable], and the primary key of this selected table [keyofTable].
Once these two steps are setup, you are then ready to use the configured
external database within your rails application.
[app/views/_form.html.erb]
...
<div class="field">
<%= f.label :personNotified %>
<%= select( "post", "personNotified", Employee.find(:all, :select => 'p_empno, p_fname, p_lname',
:order => 'p_lname').map{|emp| [emp.p_lname + " " + emp.p_fname,emp.p_empno]},
{:include_blank=>true}) %>
</div>
...
Alternatively, this way works as well...
[app/views/_form.html.erb]
...
<div class="field">
<%= f.label :personNotified_id %><br />
<%= select( "post", "personNotified_id",
User.find(:all,
:params => {:key => "vidlog-rpt"},
:select => 'id,name,last_name',
:order => 'last_name').sort_by{|user| user.last_name}.map{|emp| [emp.name,emp.id]},
{:include_blank=>true}) %>
</div>
...
The external database connection will then work like any other
database connection within rails [Employee.find...]. So long as these
database connections do not need to be joined or otherwise connected to
other databases, such external databases are fairly easy to setup and
use. If you need to link such an external database to a local database
used by rails, this gets a lot more complex.
Can Birds-Eye.Net help you or your Company?
Receive your Birds-Eye.Net articles and white
papers hot off
the presses by adding our RSS feed to your reader.
|
|