Sunday, July 9, 2017

4. Build a Rails application to accept book information viz. accession number, title, authors, edition and publisher from a web page and store the information in a database and to search for a book with the title specified by the user and to display the search results with proper headings.

After Installing rails application, you have to start the servers both Apache and MySql when you open exe file of rails application, the servers are automatically started

Open a ruby console window

C :\Rails\rails_apps>

Type the following command
Creating Books Database
> mysql -u root

This will now show you mysql> prompt

At mysql prompt type the following

>create database book_development;

>use book_development;

>create table books(id int not null auto_increment,accno varchar(40) not null,title varchar(60) not null,author varchar(60) not null,edition varchar(60) not null,publisher varchar(5) not null,primary key(id));

Creating book Project

Now open another console window type the following command

>rails -d mysql book
>cd book

Creating controller, model and view from database

>ruby script/generate scaffold Book accno:string title:string author:string
edition:string publisher:string

Starting rails server
>ruby script/server

Executing in the web browser
http://localhost:3000/books

Creating main (new) controller for searching book
>ruby script/generate controller main

a controller with a name main will be created..
Opening main controller program
>edit app\controllers\main_controller.rb

Create two views welcome and result

class MainController < ApplicationController
def welcome
@num_books = Book.count
end
def result
@titlename = params[:title]
@bookz = Book.find(:all, :conditions => "title = #{@titlename}")
end
end

Create Result view file
>notepad app\views\main\result.rhtml
<html>
<title> Welcome template for books </title>
<body>
<p> Entered book title is <%= @titlename %> </p>
<table border=1>
<tr><th>Book Id</th> <th>Accesion Number</th><th>Book
Title</th><th>Author</th> <th>Edition </th> <th>Publisher</th></tr>
<% @names.each do |bk|
@id = bk.id
@accno = bk.accno
@title = bk.title
@author = bk.author
@edition = bk.edition
@publisher = bk.publisher%>
<tr>
<td> <%= @id %></td>
<td><%= @accno %> </td>
<td><%= @title %></td>
<td> <%= @author %></td>
<td><%= @edition %></td>
<td> <%= @publisher %></td>
</tr>
<% end %>
</table>
</form></body></html>

Create Welcome view file

>notepad app\views\main\welcome.rhtml
<html>
<title> Welcome template for books </title>
<body>
<p> Total number of books = <%= @num_books %> </p>
<form action = "result" >
Enter Searching Element: <input type="text" name="title" />
<input type=submit value="Search" />
</form></body></html>

Starting Rails Server
ruby script/server

Executing in the web browser
http://localhost:3000/main/welcome

1 comment: