0% found this document useful (0 votes)
86 views

Introduction To Database, Migration, Controller and Routes in Rails

The document provides an introduction to database setup, active records, migrations, controllers, and routes in Ruby on Rails. It discusses creating MySQL and PostgreSQL databases, configuring database.yml files, generating active record models and associations, running migrations to update the database schema, generating controllers to handle requests, and defining routes to map URLs to controller actions. Key topics covered include using commands to create databases, validate model data, track schema changes, and list defined routes.

Uploaded by

Urvashi Bhardwaj
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
86 views

Introduction To Database, Migration, Controller and Routes in Rails

The document provides an introduction to database setup, active records, migrations, controllers, and routes in Ruby on Rails. It discusses creating MySQL and PostgreSQL databases, configuring database.yml files, generating active record models and associations, running migrations to update the database schema, generating controllers to handle requests, and defining routes to map URLs to controller actions. Key topics covered include using commands to create databases, validate model data, track schema changes, and list defined routes.

Uploaded by

Urvashi Bhardwaj
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 20

Chapter 5.

Introduction to
Database, Migration,
Controller and Routes in
Rails
Aim
To train the students in setting up the MySQL and
PostgreSQL databases and exercise with the active records,
migrations, controllers and routes in Rails
Instructional Objectives
Objectives of this chapter are:
• Illustrate the database setup of MySQL and PostgreSQL in Rails

• Describe the working functionality of Rails active records,


migrations, controllers and routes in Rails
Illustrate the database setup of MySQL
and PostgreSQL in Rails
Database Setup for MySQL
To Create Database in MySQL use the following command.

mysql> create database library_development;


Query OK, 1 row affected (0.01 sec)

mysql> grant all privileges on library_development.*


to 'root'@'localhost' identified by 'password';
Query OK, 0 rows affected (0.00 sec)

mysql> FLUSH PRIVILEGES;


Query OK, 0 rows affected (0.00 sec)
Database Setup for MySQL
Configuring database.yml

development: production:
adapter: mysql adapter: mysql
database:library_development database:
username: root library_production
password: [password] username: root
host: localhost test: password: [password]
adapter: mysql host: localhost
database: library_test
username: root
password: [password]
host: localhost
Database Setup for PostgreSQL
To create a new users and password for the new user follow the given commands .
tp> sudo -u postgres createuser rubyuser –s
tp> sudo -u postgres psql
postgres=# \password rubyuser

To create the databases use the following command.


postgres=# CREATE DATABASE library_development OWNER rubyuser;
postgres=# CREATE DATABASE library_production OWNER rubyuser;
postgres=# CREATE DATABASE library_test OWNER rubyuser;

Press Ctrl+D to terminate the PosgreSQL.


Database Setup for PostgreSQL
Configuring database.yml

default: &default production:


adapter: postgresql adapter: postgresql
encoding: unicode encoding: unicode
database:
library_production
development: test: username: rubyuser
adapter: postgresql adapter: postgresql password: <Password
encoding: unicode encoding: unicode for rubyuser>
database: database: library_test
library_development username: rubyuser
username: rubyuser password: <Password
password: <Password for rubyuser>
for rubyuser>
Quiz / Assessment

1) Which command is used for showing current date and time in Mysql
command line tool?
a) select now b) select now( )
c) SELECT NOW( ); d) SELECT NOW( )
2) State whether the given statement is true or false
Sqlite3 is a default database for Ruby on Rails.
a) True b) False
Describe the working
functionality of Rails active
records, migrations, controllers
and routes in Rails
Active Records
To create the Active Record files for the entities of library application, input the following
command from the top level of the application directory.
library\> rails generate model Book
library\> rails generate model Subject

Open and see the book.rb and subject.rb file in any text editor, following template is visible.
book.rb:
class Book < ActiveRecord
end
subject.rb:
class Subject < ActiveRecord
end
Active Records
Creating Associations between Models- To edit or modify the book.rb and subject.rb as follows:
class Book < ActiveRecord class Book < ActiveRecord
belongs_to :subject belongs_to :subject
end end

Implementing Validations on Models-Now open book.rb in the app\model subdirectory and


include the following validations.
class Book < ActiveRecord::Base
belongs_to :subject
validates_presence_of :title
validates_numericality_of :price, :message=>"Error Message"
end
validates_presence_of: protects "NOT NULL" fields against missing user input.
validates_numericality_of: prevents the user, entering non numeric data.
Migrations
Following is the syntax for creating migration in Rails.
application_dir> rails generate migration table_name

Following syntax is used to migrate.


C:\Sites\library> rails generate migration books

To run Migration, go to a command prompt and go to the library directory in which the application
is located, and then type the command as follows:
library> rake db:migrate
This will create a "schema_info" table, which tracks the current version of the database and each
new migration will be a new version, and any new migrations will run until the database is at the
current version.
Controllers- Characteristics

Responsible for routing external requests to internal actions

Processes the requested URLs significantly well

Manages caching very well and increases applications performance

Manages sessions, giving users the impression of an ongoing interaction


with the applications.
Controllers
The command to create controller for the library application is
C:\Sites\library> rails generate controller Book

The above command creates a file called book_controller.rb in library’s app/controllers directory.
Open and see the file, the following snippet is found:
class BookController < ApplicationController
end
Routes
To define the routes for those actions which are defined as methods in the BookController class,
Open the routes.rb file in library/config/ directory and edit it with the following lines of code:
Rails.application.routes.draw do
get 'book/list'
get 'book/new'
post 'book/create'
patch 'book/update'
get 'book/list'
get 'book/show'
get 'book/edit'
get 'book/delete'
get 'book/update'
get 'book/show_subjects'
End
Routes

Use the following command to list all the defined routes, which are useful for tracking down routing
problems in the application.

C:\Sites\library> rake routes


Quiz / Assessment

1) __________ is responsible for routing external requests to internal actions.


a) View b) Controller
c) Model d) None of the given option

2) State whether the given statement is true or false


Generate routes command is used to list all the defined routes.
a) True b) False
Summary
 PostgreSQL database does not provide any users.
 Active Record in Ruby on Rails is M in MVC, i.e. the model. The model is the layer of the system
which is responsible for handling business data and logic.
 ORM is a technique that connects the rich objects of an application to tables in a relational
database management system (RDBMS).
 Migrations are a convenient way to alter the database in a structured and organized manner.
 The Rails controller is just a logical centre of an application. It facilitate the interaction between the
user, the views, and the model.
 The Rails router recognizes URLs and dispatches them to a controller's action, or to a Rack
application.
e-References
• Database Migrations.Retrieved July 5, 2017, from
https://https://laravel.com/docs/5.4/migrations

• Active Record Bascis, Retrieved July 5 , 2017, from


http://guides.rubyonrails.org/active_record_basics.html

• Postgresql, Retrieved July 5 , 2017, from


https://www.postgresql.org/about/

You might also like