Tuesday 29 May 2012

Getting Started with Ruby on Rails


Welcome,

Ruby on Rails is an extremely productive web application framework written in Ruby by David Heinemeier Hansson.
This is a open source Ruby framework for developing database-backed web applications.

To develop a web application using Ruby on Rails Framework, install the following software:
  • Ruby
  • The Rails framework
  • A Web Server
  • A Database System
We assume that you already have installed a Web Server and Database System on your computer. You can always use the WEBrick Web Server, which comes with Ruby. Most sites, however, use Apache or lightTPD in production.

Rails works with many database systems, including MySQL,PostgreSQL, SQLite, Oracle, DB2 and SQL Server. Please refer to a corresponding Database System Setup manual to setup your database.
Let's look at the installation instructions for Rails on Windows, Mac OS X, and Linux.

Rails Installation on Windows:

  1. First, let's check to see if you already have Ruby installed. Bring up a command prompt and type ruby -v. If Ruby responds, and if it shows a version number at or above 1.8.2 then type gem --version. If you don't get an error, skip to step 3. Otherwise, we'll install a fresh Ruby.
  2. If Ruby is not installed, then download an installation package from rubyinstaller.rubyforge.org. Follow thedownload link, and run the resulting installer. This is an exe like ruby186-25.exe and will be installed in a single click. You may as well install everything . It's a very small package, and you'll get RubyGems as well alongwith this package. 
  3. With RubyGems loaded, you can install all of Rails and its dependencies through the command line:
C:\> gem install rails --include-dependencies
NOTE: Above command may take some time to install all dependencies. Make sure you are connected to the internet while installing gems dependencies.
Congratulations! You are now on Rails over Windows.

Rails Installation on Mac OS X:

  1. First, let's check to see if you already have Ruby installed. Bring up a command prompt and type ruby -v. If Ruby responds, and if it shows a version number at or above 1.8.2 then skip to step 3. Otherwise, we'll install a fresh Ruby. To install a fresh copy of Ruby, the Unix instructions that follow should help.
  2. Next you have to install RubyGems. Go to rubygems.rubyforge.org and follow the download link. OS X will typically unpack the archive file for you, so all you have to do is navigate to the downloaded directory and (in the Terminal application) type.
tp> tar xzf rubygems-x.y.z.tar.gz
tp> cd rubygems-x.y.z
rubygems-x.y.z> sudo ruby setup.rb
  1. Now use RubyGems to install Rails. Still in the Terminal application, issue the following command.
tp> sudo gem install rails --include-dependencies
NOTE: Above command may take some time to install all dependencies. Make sure you are connected to the internet while installing gems dependencies.
Congratulations! You are now on Rails over Mac OS X.

Rails Installation on Linux:

  1. First, let's check to see if you already have Ruby installed. Bring up a command prompt and type ruby -v. If Ruby responds, and if it shows a version number at or above 1.8.2 then skip to step 3. Otherwise, we'll install a fresh Ruby.
  2. Download ruby-x.y.z.tar.gz from www.ruby-lang.org
  3. Untar the distribution, and enter the top-level directory.
  4. Do the usual open-source build as follows
tp> tar -xzf ruby-x.y.z.tar.gz
tp> cd ruby-x.y.z
ruby-x.y.z> ./configure
ruby-x.y.z> make
ruby-x.y.z> make test
ruby-x.y.z> make install
  1. Install RubyGems. Go to rubygems.rubyforge.org, and follow the download link. Once you have the file locally, enter the following in your shell window.
tp> tar -xzf rubygems-0.8.10.tar.gz
tp> cd rubygems-0.8.10
rubygems-0.8.10> ruby setup.rb
  1. Now use RubyGems to install Rails. Still in the shell, issue the following command.
tp> gem install rails --include-dependencies
NOTE: Above command may take some time to install all dependencies. Make sure you are connected to the internet while installing gems dependencies.
Congratulations! You are now on Rails over Linux.

Keeping Rails Up-to-Date:

Assuming you installed Rails using RubyGems, keeping up-to-date is relatively easy. Issue the following command:
tp> gem update rails
This will automatically update your Rails installation. The next time you restart your application it will pick up this latest version of Rails. While giving this command, make sure you are connected to the internet.

Installation Verification

You can verify if everything is setup according to your requirements or not. Use the following command to create a demo project.
tp> rails demo
This will generate a demo rail project, we will discuss about it later. Currently we have to check if environment is setup or not. Now next use the following command to run WEBrick web server on your machine.
tp> cd demo
tp> ruby script/server
=> Rails application started on http://0.0.0.0:3000
=> Ctrl-C to shutdown server; call with --help for options
[2007-02-26 09:16:43] INFO WEBrick 1.3.1
[2007-02-26 09:16:43] INFO ruby 1.8.2 (2004-08-24)...
[2007-02-26 09:16:43] INFO WEBrick::HTTPServer-start:pid=2836...
....
Now open your browser and type the following address text box.
http://localhost:3000
If everything is fine then you should have a message something like "Welcome aboard" or "Congratulations".



While you're developing Rails applications, especially those which are mainly providing you with a simple interface to data in a database, it can often be useful to use the scaffold method.
Scaffolding provides more than cheap demo thrills. Here are some benefits:
  • You can quickly get code in front of your users for feedback.
  • You are motivated by faster success.
  • You can learn how Rails works by looking at generated code.
  • You can use the scaffolding as a foundation to jumpstarts your development.

Scaffolding Example:

To understand scaffolding lets create a database called cookbook and a table called recipes:

Creating an Empty Rails Web Application:

Open a command window and navigate to where you want to create this cookbook web application. I used c:\ruby. So run the following command to create complete directory structure.
C:\ruby> rails cookbook

Setting up the Database:

Here is the way to create database:
mysql> create database cookbook;
Query OK, 1 row affected (0.01 sec)

mysql> grant all privileges on cookbook.*
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)
To tell Rails how to find the database, edit the configuration file c:\ruby\cookbook\config\database.yml and change the database name to cookbook. Leave the password empty. When you finish, it should look something like
development:
  adapter: mysql
  database: cookbook
  username: root
  password: [password]
  host: localhost
test:
  adapter: mysql
  database: cookbook
  username: root
  password: [password]
  host: localhost
production:
  adapter: mysql
  database: cookbook
  username: root
  password: [password]
  host: localhost
Rails lets you run in development mode, test mode, or production mode, using different databases. This application uses the same database for each.

Creating the database tables:

We will use following table for our practical purpose. So create recipes table from sql prompt as follows:
mysql> USE cookbook;
Changed database
mysql> CREATE TABLE recipes (
    -> id INT(11) NOT NULL AUTO_INCREMENT,
    -> title VARCHAR(40),
    -> instructions VARCHAR(255),
    -> PRIMARY KEY (id));
Query OK, 0 rows affected (0.06 Sec)
NOTE: If you wish you can use Rails Migrations to create and maintain tables.

Creating Model:

First, create a Recipe model class that will hold data from the recipes table in the database. Use the following command inside cookbook directory.
C:\ruby\cookbook > ruby script\generate model Recipe
Notice that you are capitalizing Recipe and using the singular form. This is a Rails paradigm that you should follow each time you create a model.
This will create a file named app/models/recipe.rb containing a skeleton definition for the Recipe class.

Creating Controller:

Now we have to create a recipe controller with actions to manipulate the recipes in the database via the standard CRUD operations: create, read, update, and delete.
C:\ruby\cookbook > ruby script\generate controller Recipe
Notice that you are capitalizing Recipe and using the singular form. This is a Rails paradigm that you should follow each time you create a controller.
This will create a file named app/controllers/recipe_controller.rb containing a skeleton definition for the RecipeController class. Edit this file and add the line scaffold:recipe as shown
class RecipeController < ApplicationController
   scaffold:recipe
end
This single line of code will bring the database table to life. This will provide with a simple interface to your data, and ways of:
  • Creating new entries
  • Editing current entries
  • Viewing current entries
  • Destroying current entries
When creating or editing an entry, scaffold will do all the hard work of form generation and handling for you, and will even provide clever form generation, supporting the following types of inputs:
  • Simple text strings
  • Textareas (or large blocks of text)
  • Date selectors
  • Datetime selectors
Now go into cookbook directory and run Web Server using following command:
C:\ruby\cookbook> ruby script/server
Now open a browser and navigate to http://127.0.0.1:3000/recipe/new, This will provide you a screen to create new entries in recipes table. A screen shot is shown below:



Once you press Create button to create anew recipe, your record is added into recipes table and it shows following result:


You can see option to edit, show and destroy the records. So play around these options.
You can also list down all the recipes available in the recipes table using URL http://127.0.0.1:3000/recipe/list

Saturday 19 May 2012

Blog Tutorial using CakePHP

Welcome,


In this blog we will learn  Blog Application


This blog will walk you through the creation of a simple blog application. We’ll be getting and installing Cake, creating and configuring a database, and creating enough application logic to list, add, edit, and delete blog posts.


 STEPS
1.Create a Post Model
2.Create a Posts controller
3.Creating Post Views
4.Adding Posts
5.Data Validation
6.Editing Posts
7.Deleting Posts
8.Setting Routes


Create a Post Model


CakePHP’s model class files go in /app/Model, and the file we’ll be creating will be saved to /app/Model/Post.php. The completed file should look like this:
<?php
class Post extends AppModel {
}
Naming convention is very important in CakePHP. By naming our model Post, CakePHP can automatically infer that this model will be used in the PostsController, and will be tied to a database table called posts


Create a Posts Controller
Next, we’ll create a controller for our posts. The controller is where all the business logic for post interaction will happen. In a nutshell, it’s the place where you play with the models and get post-related work done. We’ll place this new controller in a file called PostsController.php inside the /app/Controller directory.
Now, lets add an action to our controller. Actions often represent a single function or interface in an application. For example, when users request www.example.com/posts/index (which is also the same as www.example.com/posts/), they might expect to see a listing of posts. The code for that action would look something like this: 



<?php
class PostsController extends AppController {
    public function index() {
        $this->set('posts', $this->Post->find('all'));
$this->set('title_for_layout','our blog title');

  }
Let me explain the action a bit. By defining function index() in our PostsController, users can now access the logic there by requesting www.example.com/posts/index. Similarly, if we were to define a function called foobar(), users would be able to access that at www.example.com/posts/foobar.
The single instruction in the action uses set() to pass data from the controller to the view (which we’ll create next). The line sets the view variable called ‘posts’ equal to the return value of the find('all') method of the Post model. Our Post model is automatically available at $this->Post because we’ve followed Cake’s naming conventions.


Creating Post Views
Now that we have our data flowing to our model, and our application logic and flow defined by our controller, let’s create a view for the index action we created above.
Cake’s view files are stored in /app/View inside a folder named after the controller they correspond to (we’ll have to create a folder named ‘Posts’ in this case). To format this post data in a nice table, our view code might look something like this:




<!-- File: /app/View/Posts/index.ctp -->

<h1>Blog posts</h1>
<p><?php echo $this->Html->link("Add Post", array('action' => 'add')); ?></p>
<table>
    <tr>
        <th>Id</th>
        <th>Title</th>
                <th>Action</th>
        <th>Created   &nbsp &nbsp &nbsp  Modified</th>
    </tr>

<!-- Here's where we loop through our $posts array, printing out post info -->

<?php foreach ($posts as $post): ?>
    <tr>
        <td><?php echo $post['Post']['id']; ?></td> 
    </tr>
<?php endforeach; ?>

</table>

Now let’s create the view for our new ‘view’ action and place it in /app/View/Posts/view.ctp.

<!-- File: /app/View/Posts/view.ctp -->
<h1><?php echo h($post['Post']['title'])?></h1>
<p><?php echo h($post['Post']['body'])?></p>

<p><small>Created: <?php echo $post['Post']['created']?></small></p>
Last modified on: <?php echo $post['Post']['modified']?></small></p>
</br>
<p>
<?php echo $html->link('back',array('action'=>'index'));?> 
<?php echo $html->link('edit',array('action'=>'edit',$post['Post']['id']));?>
<?php echo $html->link('delete',array('action'=>'delete',$post['Post']['id']));?>

</P>
 We’ll create it in the PostsController now:
<?php
class PostsController extends AppController {


    
    public function index() {
        $this->set('posts', $this->Post->find('all'));
$this->set('title_for_layout','our blog title');

  }


    public function view($id) {
        $this->Post->id = $id;
        $this->set('post', $this->Post->read());

}


Go to index file and update


<!-- File: /app/View/Posts/index.ctp -->
<td>
            <?php echo $this->Html->link($post['Post']['title'], array('action' => 'view', $post['Post']['id']));?>
        </td>
Adding Posts
Reading from the database and showing us the posts is a great start, but let’s allow for the adding of new posts.
First, start by creating an add() action in the PostsController:
public function add() {
        if (!empty($this->data)){
            if ($this->Post->save($this->data)) {
                $this->Session->setFlash('Your post has been saved.');
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash('Unable to add your post.');


} }
$this->set('title_for_layout','our blog title');
    }
Here’s what the add() action does: if HTTP method of the request was POST, try to save the data using the Post model. If for some reason it doesn’t save, just render the view. This gives us a chance to show the user validation errors or other warnings.
Every CakePHP request includes a CakeRequest object which is accessible using $this->request. The request object contains useful information regarding the request that was just received, and can be used to control the flow of your application. In this case, we use the CakeRequest::is() method to check that the request is a HTTP POST request.
When a user uses a form to POST data to your application, that information is available in $this->request->data. You can use the pr() or debug() functions to print it out if you want to see what it looks like.
We use the SessionComponent’s SessionComponent::setFlash() method to set a message to a session variable to be displayed on the page after redirection. In the layout we have SessionHelper::flash which displays the message and clears the corresponding session variable. The controller’s Controller::redirect function redirects to another URL. The param array('action' => 'index') translates to URL /posts i.e the index action of posts controller. You can refer to Router::url() function on the api to see the formats in which you can specify a URL for various cake functions.
Calling the save() method will check for validation errors and abort the save if any occur. We’ll discuss how those errors are handled in the following sections.
Data Validation
It will ensure that the data which your inserting is mantatory or not..something like * options
<!-- File: /app/View/Posts/add.ctp -->
<h1>Add Post</h1>
<?php
echo $this->Form->create('Post');
echo $this->Form->input('title');
echo $this->Form->input('body', array('rows' => '3'));
echo $this->Form->end('Save Post');
?>

Editing Posts

First, start by creating an edit() action in the PostsController:


function edit($id = null) {

   if (empty($this->data)){

   $this->data = $this->Post->read(null,$id);

   }

   else {
   if ($this->Post->save($this->request->data)) {
            $this->Session->setFlash('Your post has been updated.');
            $this->redirect(array('action' => 'index'));
} else {
            $this->Session->setFlash('Unable to update your post.');
        }
    }

   }
This action first checks that the request is a GET request. If it is, then we find the Post and hand it to the view. If the user request is not a GET, it probably contains POST data. We’ll use the POST data to update our Post record with, or kick back and show the user the validation errors.
The edit view might look something like this:
<!-- File: /app/View/Posts/edit.ctp -->

<h1>Edit Post</h1>

<?php

    echo $this->Form->create('Post', array('action' => 'edit'));

    echo $this->Form->input('title');

    echo $this->Form->input('body');
echo $this->Form->input('id', array('type' => 'hidden'));
    echo $this->Form->end('Save Post');
This view outputs the edit form (with the values populated), along with any necessary validation error messages.
One thing to note here: CakePHP will assume that you are editing a model if the ‘id’ field is present in the data array. If no ‘id’ is present (look back at our add view), Cake will assume that you are inserting a new model whensave() is called.
Go to index file and update
<!-- File: /app/View/Posts/index.ctp -->
<td>
            <?php echo $this->Html->link('Edit', array('action' => 'edit', $post['Post']['id']));?>
        </td>
Deleting Posts
Start with a delete() action in the PostsController:

 function delete($id = null) {
   $this->Post->delete($id) ;
        $this->Session->setFlash('The post with id: ' . $id . ' has been deleted.');
        $this->redirect(array('action' => 'index'));
    }   
}
Go to index file and update
<!-- File: /app/View/Posts/index.ctp -->
 <td>
           <?php echo $post['Post']['created']; ?>
   <?php echo $this->Html->link('delete', array('action' => 'delete', $post['Post']['id']),NULL,'Are  u sure u want to delete this post?');?>
        </td>
Setting Routes
For some, CakePHP’s default routing works well enough. Developers who are sensitive to user-friendliness and general search engine compatibility will appreciate the way that CakePHP’s URLs map to specific actions. So we’ll just make a quick change to routes in this tutorial.
For more information on advanced routing techniques, see Routes Configuration.
By default, CakePHP responds to a request for the root of your site (i.e. http://www.example.com) using its PagesController, rendering a view called “home”. Instead, we’ll replace this with our PostsController by creating a routing rule.
Cake’s routing is found in /app/Config/routes.php. You’ll want to comment out or remove the line that defines the default root route. It looks like this:
<?php
Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home'));
This line connects the URL ‘/’ with the default CakePHP home page. We want it to connect with our own controller, so replace that line with this one:
<?php
Router::connect('/', array('controller' => 'posts', 'action' => 'index'));
This should connect users requesting ‘/’ to the index() action of our PostsController.


For better understanding go through online tutorials links are given below:
cakephp tutorial 2
cakephp tutorial 3
cakephp tutorial 4
cakephp tutorial 5
cakephp tutorial 6
cakephp tutorial 7
cakephp tutorial 8