Pages

Showing posts with label Rails. Show all posts
Showing posts with label Rails. Show all posts

Friday, August 6, 2010

Rails Application with MySQL DB

Follow the following step to work on rails application with mysql.





1:Our system should have the ruby installed .If not install the ruby from here
2: Start a Command prompt with Ruby C:\Ruby\bin
3:Enter the following command to install the special version of MySQL bindings.
      gem install mysql
You should expect a similar output like this:
  Successfully installed mysql-2.8.1.1-x86-mingw32
  1 gem installed
4:Enter the following command to install rails
     gem install rails
This is going to take a bit, since Rails and it’s dependencies takes around 2MB or so, and need to be downloaded and
installed.
Once done, expect see at the screen something like this:
  Successfully installed activSupport-2.3.2
  Successfully installed activerecord-2.3.2
  Successfully installed actionpack-2.3.2
  Successfully installed actionmailer-2.3.2
  Successfully installed activeresource-2.3.2
  Successfully installed rails-2.3.2
  6 gems installed
5:Copy the libmySQL.dll file from here
and paste it in your c:\ruby\bin location.
6:Create a rails application with mysql .Create a new Folder RailsPrg in C:

In Command prompt switch to C:\RailsPrg>
Let’s name our application appInMySQL
      rails appInMySQL --database=mysql
The --database option indicates to Rails that we want to use
MySQL instead of the default database adapter (SQLite3).
Rails will output a lot of lines when creating your application
structure, just an excerpt of what to see:
  ...
   create config/database.yml
   create config/routes.rb
   create config/locales/en.yml
   create config/initializers/backtrace_silencers.rb
   create config/initializers/inflections.rb
   create config/initializers/mime_types.rb
   create config/initializers/new_rails_defaults.rb
   create config/initializers/session_store.rb
   create config/environment.rb
   ...
7:Now Rails have configured for us the name of the database we want to use, and you can verify it in appInMySQL\config\database.yml
In that database.yml file modify as you need in the development phase
development:
   adapter: mysql
   encoding: utf8
   reconnect: false
   database: testMySql
   pool: 5
   username: username
   password: password
   host: hostname
8:In command prompt switch to C:\RailsPrg\appInMySQL> type the command
      rake db:create
Just that, simple db:create is going to connect to our MySQL server, and create the database for us.
9:Let’s verify that everything is in place, using the following command:


     ruby script\about
We can see the something like this as result:
About your application's environment
  Ruby version 1.9.1 (i386-mingw32)
  RubyGems version 1.3.4
  Rack version 1.0 bundled
  Rails version 2.3.2
  Active Record version 2.3.2
  Action Pack version 2.3.2
  Active Resource version 2.3.2
  Action Mailer version 2.3.2
  Active Support version 2.3.2
  Application root C:\RailsPrg\appInMySQL
  Environment development
  Database adapter mysql
  Database schema version 0
10:Now we can start generating the table for our application
Command to create a table & generate the pages for performing operation like inserting, deleting & modifying
Table name is cart
    ruby script\generate scaffold cart cartId:integer productInCart:string
Enter the migrate command
    rake db:migrate
11:Command to start the server ruby script\server
12:Execute http://localhost:3000/carts/ =>You can see the application page & can refine further the application

Thursday, July 15, 2010

Ruby On Rails for Beginners

Rails is a web-application framework that includes everything needed to create database-backed web applications according to the Model-View-Control pattern.
Rails is a collection ruby script. It’s better to have basic idea of ruby language before entering into Rails.
Rails has the following things

1. An Application framework /Action Pack that will help us to
generate data-driven, interactive pages.
2. Rails comes with one build in WebServer -We can run the web
application
3. Database-Rails creates application that are configured to
work with an integrated SQLite3 database
4. Active Record-Rails provides for object-relational mapping
library. This makes the database like a collection of Ruby objects.
5. Rails also provide the collection of tool scripts that helps
to manage the application.

Principle in Rails: Don’t Repeat Yourself
[If we tell Rails something once,its not required to say it again]

Install Ruby on Rails or RoR version2.1 & SQLite3 for database
http://www.rubyonrails.org/down

Getting started with Application

I - Steps to create a new application in Rails
1. At a Command Prompt –type >rails Application name
  Ex: C:\ >rails MyApp

A New Folder names MyApp will be created with basic structure of the
application.
The basic Structure has the following folders &files
App,Config,Db,Doc,Lib,Log,Public,Script, test, tmp, vendor ,Rake files & readme
file

2.In that command prompt change into MyApp folder C:\MyApp>.
Type ruby script/server –To run the web server.

  Ex: C:\MyApp>ruby script/server

3.Check this link http://localhost:3000/ to
confirm whether the webserver running Rails starts its webserver on port 3000 by default.

II -Start developing the Application

CRUD operation
CRUD operation/ Scaffolding –Basic operation of an application
Create,Read,Update & Delete.
Type scaffold command _Will generate the code for doing CRUD
operation in a database and also in the presentation layer .

 Ex: C:\MyApp\>ruby script/generate scaffold employee employee_name:string
address:text

Creates employee.rb file in models & create_employees.rb
file in Db -migrate

[Note: We have to give the db name in singular form like
Employee,Shop..etc., and the table name will be in plural like
employees,Shops..etc.,]

To create the Tables in the database

We have to run the migration script using another rails tool called Rake.This
migration ruby script is generated by the scaffolding.

Type rake db:migrate at the command prompt –Which runs the
migration code& creates the table.[Db files are location the db folder]

  Ex:C:\MyApp\>rake db:migrate

 Run the employees.rb file in Db –migrate & create the table.

Go for link http://localhost:3000/employees In a couple of minutes we
can enter few records & perform the CRUD operations.


In app folder we will have Model, Controller & View folders .

To changes the display of the page

We can make the changes in the labels by changing the four .html.erb files in
the views folder.

To append a column after creating the Table.
Rails understand the migration Add..To..=>Add particular column
to a particular table.
Ex:If we want to include Phone Number column in employees table.

  C:\MyApp\>ruby script/generate migration
AddPhoneToEmployees phone:string
Rails write the migration code.

After this command we have to give Rake db:migrate to make the
reflection of new column in the table.
Go for link http://localhost:3000/employees to conifrm the addition of
one more column in the table.
We can check the changes whenever we update the code.No need for publish & deploy
operations.

Without Scaffolding
We are in some time need of writing the code by our self for some application.Instead of having the same basic CRUD functions.We might be in need of genearating our own models & controllers

Command to create own model
 ruby script/generate model table name in singular form column name:type

>  rake db:migrate

This command will create magic columns
 Id – Generated Primary Key.
 Created_at and updated_at – record when data is entered or updated

Command to create own controller
ruby script/generate controller
A Controller file will be created in the controller folder.

III- Routes
Route tells Tails where the web pages are located.
Routes are defined in a ruby program in config/routes.rb

By default this two line swill be the routes.rb

  map.connect ':controller/:action/:id'
  map.connect ':controller/:action/:id.:format'

We can specify our own routes.
 Ex:map.connect '/employees/:id',:controller=>'employees',:action=>'show'

The controller by using the finder method in the model sends the employees to the view

employees_controller.rb file

 Class employeesController < ApplicationController
  Def show
    @employee=Employee.find(params[:id])
   end
 end


Rails Layout
Super-template exists in Rails is called Layout. one Single
template that will control how a group of other templates will look.
We have to place the html.erb file in the app/views/layouts.

To Add the style-sheet in the
Style sheet, images & javascripts will resides in the public folder.Which has all the static files.
Include the following code in the head tag of the html template.
   <%=stylesheet_link_tag 'style sheet name(css)'>


Redirect
A redirect tells the browser to go to a different URL for output.
  redirect_to "/---/# {---}"
# -symbol and {} inserts the value of the variable into a string.
Ex: While creating a new sample .We have to redirect to the currently
created sample.

 def create
  @sample = Sample.new(params[:sample])
  @sample.save
  redirect_to "/samples/#{@sample.id}"
 end


Restricting access to a function
Rails will use special kind of web security called HTTP Authenticating .This type of security will pops up a dialog box and asks for a username and password when someone tries to enter a secure area of a website.
In the controller we have to specify the following code to make the filtration before doing security applied functions.

before_filter :function name to be called before executing particular function,;only=>[:security applied operation name]

function name to be called before particular operations

 def functionname
  authenticate_or_request_with_http_basic("The name of the secured area of the website-domain") do |username,password|
    username == "username "&& password =="password"
   end
 end

Ex:

 class SampleController <ApplicationController before_filter   check_logged_in,:only=>[:edit]
  def check_logged_in
    authenticate_or_request_with_http_basic("Samples") do |username,password|
   username == 'admin' && password =="XY2HYS8"
  end
  end
 end