Pages

Monday, December 28, 2009

How to Connect and View an existing database in Rails.

Before we start, you should have all the dependencies installed
(Ruby , Rubygems, and also Rails ) for more info ,
http://rubyonrails.org/download.and the database.
In my example i will be using MySQL as the RDBMS.

1) create the project.

>> rails demo --database=mysql

2) Open your /demo/config/database.yml and edit it to connect to your database. For example

development:
adapter: mysql
database: prototype
pool: 5
host: localhost
username:
password:
socket: /var/run/mysqld/mysqld.sock

3) Okay now.you already have an application which connected to your database but you need to create the model for your table. So here's the
command to create the model.

>> ruby script/generate model tablename --skip-migration

p/s : I would use --skip-migration just in case you run the rake db:migrate which would cause your data in the table to be
wipe out.

4) After creating the model, create the controller. you can use whatever name you want but in this example. I put 'show' as my controller name.

>> ruby/script generate controller show

5) Since you are using your own database with your own table name, it is better to set rails to not to look for a pluralize table name.So open up your environment.rb in demo/config/environment.rb and put this line at the bottom of your environment.rb

ActiveRecord::Base.pluralize_table_names = false

6) Edit the controller to find all the data in your table.(eg: demo/app/controller/show_controller.rb)
For example I have a controller name show , a table name person. so my show_controller.rb
will look something like this :

class ShowController < ApplicationController
def index
@prototype = Person.find(:all)
end
end

7) The last step to do is to create the view , open up your demo/app/views/show/index.rhtml (notice that the name of the file .rhtml will be the same as your function name in
show_controller . In this example I use index ).

Edit the index.rhtml to something like this :











(the @prototype is the variable that you use in your show_controller and id, name, hobby, and job is the table fields ).

8 ) Open http://localhost:3000/show and you should see the data in your database on your rails application. good luck!

No comments:

Post a Comment