SlideShare une entreprise Scribd logo
1  sur  48
Télécharger pour lire hors ligne
Turbocharge your web
development with Rails
            Vagmi Mudumbai
   Dharana Software Innovations Pvt Ltd
    @vagmi / vagmi@dharanasoft.com
About me
 http://vagmim.com




RailsPundit
       ChennaiGeeks
       facebook.com/groups/chennaigeeks
http://www.catb.org/~esr/hacker-emblem/
Agenda
• About Ruby
                  • Controllers
• About Rails
                  • Layouts
• MVC
                  • Views
• Models
                  • Forms
• Relationships
                  • Q &A
• Routes
•Created by Yakuhiro
  “Matz” Matsumoto in
  1995 in Japan
•Generally available to
  the english speaking
  world at 2000
•Multi paradigm language
•Supports imperative/Object Oriented/
  Functional styles of programming
# The Greeter class
class Greeter
  def initialize(name)
    @name = name.capitalize
  end

  def salute
    puts "Hello #{@name}!"
  end
end

# Create a new object
g = Greeter.new("world")

# Output "Hello World!"
g.salute
•Many Flavors
 •MRI/YARV
 •JRuby
 •Rubinius
 •IronRuby
 •Maglev
 •And more
• Created in 2005 by
  David Heinemeier
  Hannson (a.k.a. DHH)
• A web framework to
  helps you actually
  enjoy programming
• Intended to be simple and consistent to use
• Convention over configuration
• Freedom from needless XML situps
Installing Ruby


• For windows you can get Ruby from
• http://rubyinstaller.org/
Installing Ruby

• For Linux and Mac OSX
• Install via RVM
 • http://rvm.beginrescueend.com/
 • http://amerine.net/2010/02/24/rvm-rails3-
    ruby-1-9-2-setup.html
Installing Rails


$ gem install rails
Rails MVC


            Router


           Controller


    View                Model   DB
HTML/CSS/JS
Create a Rails App


$ rails new todolist
Rails Project Structure
myapp/
|-- Gemfile    #   all the dependencies go here
|-- Rakefile   #   the build file??
|-- app        #   The entire application sits here
|-- config     #   Configure the app to your heart's content
|-- db         #   Database migrations, seed file
|-- lib        #   Custom rake tasks and your libraries
|-- log        #   The directory we all love
|-- public     #   Static assets like CSS, JS and images
|-- script     #   Contains one file "rails"
|-- test       #   Tests - unit, functional, integration
|-- tmp        #   misc stuff like sessions, pids and working files
`-- vendor     #   3rd party stuff - not used as much these days
Rails Project Structure
myapp/
`-- app
    |--   controllers                   # controllers
    |     `-- application_controller.rb
    |--   helpers
    |     `-- application_helper.rb     # view helpers
    |--   mailers
    |--   models
    `--   views
          `-- layouts
              `-- application.html.erb # could be haml or any other
                                        # templating language
Rails Project Structure
myapp/
`-- config
    |-- application.rb         # the main application config file
    |-- boot.rb                # setup bundler and the environment
    |-- database.yml           # setup database connections
    |-- environments
    |   |-- development.rb     # development specific setup
    |   |-- production.rb      # production specific setup
    |   `-- test.rb            # test specific setup
    |-- initializers
    |   |-- inflections.rb     #   any file put inside
    |   |-- mime_types.rb      #   this directory will
    |   |-- secret_token.rb    #   be executed when the
    |   `-- session_store.rb   #   rails application boots
    |-- locales
    |   `-- en.yml             # setup internationalization
    `-- routes.rb              # map URLs to Controllers/Actions
Models
Create a model
$ rails g model todo title:string done:boolean completed_at:datetime
      invoke active_record
      create    db/migrate/20110625034305_create_todos.rb
      create    app/models/todo.rb
      invoke    test_unit
      create      test/unit/todo_test.rb
      create      test/fixtures/todos.yml
class CreateTodos < ActiveRecord::Migration
  def self.up
    create_table :todos do |t|
      t.string :title
      t.boolean :done
      t.datetime :completed_at

     t.timestamps
   end
 end

  def self.down
    drop_table :todos
  end
end




            Migration
The model class

class Todo < ActiveRecord::Base
  # seriously thats it
  # rails does rest of the magic
end
Create the table
$ rake db:migrate
(in /path/to/myapp)
== CreateTodos: migrating ================
-- create_table(:todos)
   -> 0.0015s
== CreateTodos: migrated (0.0016s)
===========================================
$ rails console
Loading development environment (Rails 3.0.7)
ruby-1.9.2-p180 :001 >




        The Rails console
        The REPL for Rails
> todo=Todo.new
# => #<Todo id: nil, title: nil, done: nil,
completed_at: nil, created_at: nil, updated_at:
nil>
> todo.title="Some title"
# => "Some title"
> todo.save
# AREL (0.5ms) INSERT INTO "todos" ("title",
"done", "completed_at", "created_at",
"updated_at") VALUES ('Some title', NULL, NULL,
'2011-06-25 04:21:47.272312', '2011-06-25
04:21:47.272312')
 => true




      Create a new object
> todo = Todo.new(:title=>"Teach
Rails",:done=>true,:completed_at=>Time.now)
 => #<Todo id: nil, title: "Teach Rails", done:
true, completed_at: "2011-06-25 04:26:29",
created_at: nil, updated_at: nil>
> todo.save
  AREL (0.8ms) INSERT INTO "todos" ("title",
"done", "completed_at", "created_at", "updated_at")
VALUES ('Teach Rails', 't', '2011-06-25
04:26:29.853087', '2011-06-25 04:26:38.869335',
'2011-06-25 04:26:38.869335')
 => true




      Create a new object
Querying
> Todo.where(:done=>true).all
  Todo Load (0.4ms) SELECT "todos".* FROM
"todos" WHERE "todos"."done" = 't'
 => [#<Todo id: 2, title: "Teach Rails",
done: true, completed_at: "2011-06-25
04:26:29", created_at: "2011-06-25
04:26:38", updated_at: "2011-06-25
04:26:38">]
> t = Todo.where(:done=>true).first
  Todo Load (0.4ms) SELECT "todos".* FROM
"todos" WHERE "todos"."done" = 't' LIMIT 1
 => #<Todo id: 2, title: "Teach Rails", done:
true, completed_at: "2011-06-25 04:26:29",
created_at: "2011-06-25 04:26:38", updated_at:
"2011-06-25 04:26:38">
> t.done=false
 => false
> t.save
  AREL (0.5ms) UPDATE "todos" SET "done" =
'f', "updated_at" = '2011-06-25
05:31:07.025845' WHERE "todos"."id" = 2
 => true



    Update object
Deleting objects
> t.destroy
  AREL (0.5ms) DELETE FROM "todos" WHERE
"todos"."id" = 2
 => #<Todo id: 2, title: "Teach Rails",
done: false, completed_at: "2011-06-25
04:26:29", created_at: "2011-06-25
04:26:38", updated_at: "2011-06-25
05:31:07">
Relationships
$ rails g bucket name:string
$ rails g task title:string done:boolean bucket:references


 create_table :buckets do |t|
                                class Bucket < ActiveRecord::Base
   t.string :name
                                  has_many :tasks
   t.timestamps
                                end
 end



 create_table :tasks do |t|
   t.string :title
                                class Task < ActiveRecord::Base
   t.boolean :done
                                  belongs_to :bucket
   t.references :bucket
                                end
   t.timestamps
 end
Creating and querying relationships

> bucket = Bucket.create(:name=>"work") # create work bucket
> bucket.tasks.create(:title=>"Fill in timesheets") # create task
under bucket
> bucket.tasks.create(:title=>"Fix bug #234") #create another task
> bucket.tasks.count # => 2
> bucket.tasks
> t=Task.first # get the task object
> t.bucket # access the bucket object from the task object
Still awake?
Controllers & Routes
config/routes.rb
Myapp::Application.routes.draw do
  # direct root (/) to WelcomeController's
  # index action
  root :to => "welcome#index"
end


       $ rails g controller welcome
Welcome Controller
# app/controllers/welcome_controller.rb
class WelcomeController < ApplicationController
  def index
    render :text=>"hello world"
  end
end
Views
  # app/controller/welcome_controller.rb
  class WelcomeController <
  ApplicationController
    def index
      @time = Time.now
    end
  end

<!-- in app/views/welcome/index.html.erb -->
<h1>The time is <%=@time.strftime('%d-%b-%Y %H:%M:
%S')%></h1>
ReST and Resources
           Myapp::Application.routes.draw do
             resources :tasks
           end


$ rake routes
(in /path/to/myapp)
    tasks GET    /tasks(.:format)            {:action=>"index", :controller=>"tasks"}
          POST   /tasks(.:format)            {:action=>"create", :controller=>"tasks"}
 new_task GET    /tasks/new(.:format)        {:action=>"new", :controller=>"tasks"}
edit_task GET    /tasks/:id/edit(.:format)   {:action=>"edit", :controller=>"tasks"}
     task GET    /tasks/:id(.:format)        {:action=>"show", :controller=>"tasks"}
          PUT    /tasks/:id(.:format)        {:action=>"update", :controller=>"tasks"}
          DELETE /tasks/:id(.:format)        {:action=>"destroy", :controller=>"tasks"}
ReST and Resources
class TasksController < ApplicationController
  # index displays a list of tasks
  # new presents a form to create a task
  # create processes the form submitted by the new action
  # show displays an individual task
  # edit presents a form to update a task
  # update processes the form submitted by the edit action
  # destroy deletes a task
end
Nested resources
          Myapp::Application.routes.draw do
            resources :buckets, :shallow=>true do
              resources :tasks
            end
          end
$ rake routes
(in /path/to/myapp)
   bucket_tasks GET      /buckets/:bucket_id/tasks(.:format)       {:action=>"index", :controller=>"tasks"}
                POST     /buckets/:bucket_id/tasks(.:format)       {:action=>"create", :controller=>"tasks"}
new_bucket_task GET      /buckets/:bucket_id/tasks/new(.:format)   {:action=>"new", :controller=>"tasks"}
      edit_task GET      /tasks/:id/edit(.:format)                 {:action=>"edit", :controller=>"tasks"}
           task GET      /tasks/:id(.:format)                      {:action=>"show", :controller=>"tasks"}
                PUT      /tasks/:id(.:format)                      {:action=>"update", :controller=>"tasks"}
                DELETE   /tasks/:id(.:format)                      {:action=>"destroy", :controller=>"tasks"}
        buckets GET      /buckets(.:format)                        {:action=>"index", :controller=>"buckets"}
                POST     /buckets(.:format)                        {:action=>"create", :controller=>"buckets"}
     new_bucket GET      /buckets/new(.:format)                    {:action=>"new", :controller=>"buckets"}
    edit_bucket GET      /buckets/:id/edit(.:format)               {:action=>"edit", :controller=>"buckets"}
         bucket GET      /buckets/:id(.:format)                    {:action=>"show", :controller=>"buckets"}
                PUT      /buckets/:id(.:format)                    {:action=>"update", :controller=>"buckets"}
                DELETE   /buckets/:id(.:format)                    {:action=>"destroy", :controller=>"buckets"}

                                                                              * If you squint hard enough, you will be able to read it.
BucketsController
      def index
        @buckets = Bucket.all
      end

 def show
   @bucket=Bucket.find(params[:id])
 end

 def destroy
   @bucket=Bucket.find(params[:id])
   @bucket.destroy
   redirect_to buckets_path
 end
BucketsController
        def new
          @bucket = Bucket.new
        end

def create
  @bucket = Bucket.new(params[:bucket])
  if(@bucket.save)
    flash[:notice] = "Bucket created"
    redirect_to @bucket
  else
    render :action=>:new
  end
end
BucketsController
      def edit
        @bucket = Bucket.find(params[:id])
      end


def update
  @bucket=Bucket.find(params[:id])
  if(@bucket.update_attributes(params[:bucket]))
    flash[:notice]="Bucket updated"
    redirect_to @bucket
  else
    render :action=>:edit
  end
end
Tasks Controller
def new
  @bucket = Bucket.find(params[:bucket_id])
  @task = @bucket.tasks.build
end

def create
  @bucket = Bucket.find(params[:bucket_id])
  # the form should have passed bucket_id
  # as one of the parameters via
  # a hidden field
  @task = Task.new(params[:task])
  if(@task.save)
    flash[:notice]="task created"
    redirect_to @task
  else
    render :action=>:new
  end
end

The other actions remain the same
Fantastic Forms
Formtastic
           # add these to your
           # Gemfile
           gem 'formtastic'
           gem 'jquery-rails'

      $ rails g formtastic:install
      $ rails g jquery:install

<!-- in app/views/buckets/new.html.erb -->
<%= semantic_form_for @bucket do |f| %>
  <%= f.inputs %>
  <%= f.buttons %>
<% end %>
Hands On
Vagmi Mudumbai
            vagmi@dharanasoft.com

        twitter.com/vagmi
        facebook.com/vagmi
        linkedin.com/in/vagmi
        github.com/vagmi
        plus.google.com/
        106483555843485143380/


Thank you

Contenu connexe

Tendances

Rails web api 开发
Rails web api 开发Rails web api 开发
Rails web api 开发shaokun
 
Keeping the frontend under control with Symfony and Webpack
Keeping the frontend under control with Symfony and WebpackKeeping the frontend under control with Symfony and Webpack
Keeping the frontend under control with Symfony and WebpackIgnacio Martín
 
Rails 2.3 and Rack - NHRuby Feb 2009
Rails 2.3 and Rack - NHRuby Feb 2009Rails 2.3 and Rack - NHRuby Feb 2009
Rails 2.3 and Rack - NHRuby Feb 2009bturnbull
 
Ruby w/o Rails (Олександр Сімонов)
Ruby w/o Rails (Олександр Сімонов)Ruby w/o Rails (Олександр Сімонов)
Ruby w/o Rails (Олександр Сімонов)Fwdays
 
Building web framework with Rack
Building web framework with RackBuilding web framework with Rack
Building web framework with Racksickill
 
Modern Perl Web Development with Dancer
Modern Perl Web Development with DancerModern Perl Web Development with Dancer
Modern Perl Web Development with DancerDave Cross
 
Symfony bundle fo asynchronous job processing
Symfony bundle fo asynchronous job processingSymfony bundle fo asynchronous job processing
Symfony bundle fo asynchronous job processingWojciech Ciołko
 
Jasig rubyon rails
Jasig rubyon railsJasig rubyon rails
Jasig rubyon rails_zaMmer_
 
Introduction à Ruby
Introduction à RubyIntroduction à Ruby
Introduction à RubyMicrosoft
 
Laravel 5 In Depth
Laravel 5 In DepthLaravel 5 In Depth
Laravel 5 In DepthKirk Bushell
 
Introduction to Rails - presented by Arman Ortega
Introduction to Rails - presented by Arman OrtegaIntroduction to Rails - presented by Arman Ortega
Introduction to Rails - presented by Arman Ortegaarman o
 
Introduction to laravel framework
Introduction to laravel frameworkIntroduction to laravel framework
Introduction to laravel frameworkAhmad Fatoni
 
Advanced RESTful Rails
Advanced RESTful RailsAdvanced RESTful Rails
Advanced RESTful RailsBen Scofield
 
REST APIs in Laravel 101
REST APIs in Laravel 101REST APIs in Laravel 101
REST APIs in Laravel 101Samantha Geitz
 
Ruby conf 2011, Create your own rails framework
Ruby conf 2011, Create your own rails frameworkRuby conf 2011, Create your own rails framework
Ruby conf 2011, Create your own rails frameworkPankaj Bhageria
 

Tendances (19)

Rails web api 开发
Rails web api 开发Rails web api 开发
Rails web api 开发
 
Keeping the frontend under control with Symfony and Webpack
Keeping the frontend under control with Symfony and WebpackKeeping the frontend under control with Symfony and Webpack
Keeping the frontend under control with Symfony and Webpack
 
Rails 2.3 and Rack - NHRuby Feb 2009
Rails 2.3 and Rack - NHRuby Feb 2009Rails 2.3 and Rack - NHRuby Feb 2009
Rails 2.3 and Rack - NHRuby Feb 2009
 
Ruby w/o Rails (Олександр Сімонов)
Ruby w/o Rails (Олександр Сімонов)Ruby w/o Rails (Олександр Сімонов)
Ruby w/o Rails (Олександр Сімонов)
 
Rails3 changesets
Rails3 changesetsRails3 changesets
Rails3 changesets
 
Building web framework with Rack
Building web framework with RackBuilding web framework with Rack
Building web framework with Rack
 
Rack
RackRack
Rack
 
Modern Perl Web Development with Dancer
Modern Perl Web Development with DancerModern Perl Web Development with Dancer
Modern Perl Web Development with Dancer
 
Symfony bundle fo asynchronous job processing
Symfony bundle fo asynchronous job processingSymfony bundle fo asynchronous job processing
Symfony bundle fo asynchronous job processing
 
Jasig rubyon rails
Jasig rubyon railsJasig rubyon rails
Jasig rubyon rails
 
Intro to Rack
Intro to RackIntro to Rack
Intro to Rack
 
Introduction à Ruby
Introduction à RubyIntroduction à Ruby
Introduction à Ruby
 
Laravel 5 In Depth
Laravel 5 In DepthLaravel 5 In Depth
Laravel 5 In Depth
 
Introduction to Rails - presented by Arman Ortega
Introduction to Rails - presented by Arman OrtegaIntroduction to Rails - presented by Arman Ortega
Introduction to Rails - presented by Arman Ortega
 
Introduction to laravel framework
Introduction to laravel frameworkIntroduction to laravel framework
Introduction to laravel framework
 
Advanced RESTful Rails
Advanced RESTful RailsAdvanced RESTful Rails
Advanced RESTful Rails
 
Create a new project in ROR
Create a new project in RORCreate a new project in ROR
Create a new project in ROR
 
REST APIs in Laravel 101
REST APIs in Laravel 101REST APIs in Laravel 101
REST APIs in Laravel 101
 
Ruby conf 2011, Create your own rails framework
Ruby conf 2011, Create your own rails frameworkRuby conf 2011, Create your own rails framework
Ruby conf 2011, Create your own rails framework
 

En vedette

Github - Down the Rabbit Hole
Github  - Down the Rabbit HoleGithub  - Down the Rabbit Hole
Github - Down the Rabbit HoleVagmi Mudumbai
 
JSFoo 2014 - Building beautiful apps with Clojurescript
JSFoo 2014 - Building beautiful apps with ClojurescriptJSFoo 2014 - Building beautiful apps with Clojurescript
JSFoo 2014 - Building beautiful apps with ClojurescriptVagmi Mudumbai
 
Print maths loop games (print)
Print maths loop games (print)Print maths loop games (print)
Print maths loop games (print)Michelle Moloney
 
Real Time Analytics with Cassandra
Real Time Analytics with CassandraReal Time Analytics with Cassandra
Real Time Analytics with CassandraVagmi Mudumbai
 
Blog zero-to-blog-hero
Blog zero-to-blog-heroBlog zero-to-blog-hero
Blog zero-to-blog-heroJeff McLeod
 
MongoDB - Introduction
MongoDB - IntroductionMongoDB - Introduction
MongoDB - IntroductionVagmi Mudumbai
 
Pragmatic Functional Programming in the JS land with Clojurescript and Om
Pragmatic Functional Programming in the JS land with Clojurescript and OmPragmatic Functional Programming in the JS land with Clojurescript and Om
Pragmatic Functional Programming in the JS land with Clojurescript and OmVagmi Mudumbai
 
Building Single Page Apps with Backbone.js, Coffeescript and Rails 3.1
Building Single Page Apps with Backbone.js, Coffeescript and Rails 3.1Building Single Page Apps with Backbone.js, Coffeescript and Rails 3.1
Building Single Page Apps with Backbone.js, Coffeescript and Rails 3.1Vagmi Mudumbai
 
Crystal - Statically Typed Ruby
Crystal - Statically Typed RubyCrystal - Statically Typed Ruby
Crystal - Statically Typed RubyVagmi Mudumbai
 
Building Single Page Apps with React.JS
Building Single Page Apps with React.JSBuilding Single Page Apps with React.JS
Building Single Page Apps with React.JSVagmi Mudumbai
 
a-beginners-guide-to-namas-web_final
a-beginners-guide-to-namas-web_finala-beginners-guide-to-namas-web_final
a-beginners-guide-to-namas-web_finalUrska Trunk
 
Ruby On Rails - 1. Ruby Introduction
Ruby On Rails - 1. Ruby IntroductionRuby On Rails - 1. Ruby Introduction
Ruby On Rails - 1. Ruby IntroductionJakob
 
Ruby on Rails Introduction | FEU-EAC, February 2014
Ruby on Rails Introduction | FEU-EAC, February 2014Ruby on Rails Introduction | FEU-EAC, February 2014
Ruby on Rails Introduction | FEU-EAC, February 2014Ken-Lauren Daganio
 
Rochester on Rails: Introduction to Ruby
Rochester on Rails: Introduction to RubyRochester on Rails: Introduction to Ruby
Rochester on Rails: Introduction to RubyJason Morrison
 

En vedette (20)

Purely functional UIs
Purely functional UIsPurely functional UIs
Purely functional UIs
 
Github - Down the Rabbit Hole
Github  - Down the Rabbit HoleGithub  - Down the Rabbit Hole
Github - Down the Rabbit Hole
 
Myself
MyselfMyself
Myself
 
JSFoo 2014 - Building beautiful apps with Clojurescript
JSFoo 2014 - Building beautiful apps with ClojurescriptJSFoo 2014 - Building beautiful apps with Clojurescript
JSFoo 2014 - Building beautiful apps with Clojurescript
 
Print maths loop games (print)
Print maths loop games (print)Print maths loop games (print)
Print maths loop games (print)
 
Life expectancy
Life expectancyLife expectancy
Life expectancy
 
Real Time Analytics with Cassandra
Real Time Analytics with CassandraReal Time Analytics with Cassandra
Real Time Analytics with Cassandra
 
Introduction to JRuby
Introduction to JRubyIntroduction to JRuby
Introduction to JRuby
 
Blog zero-to-blog-hero
Blog zero-to-blog-heroBlog zero-to-blog-hero
Blog zero-to-blog-hero
 
MongoDB - Introduction
MongoDB - IntroductionMongoDB - Introduction
MongoDB - Introduction
 
Pragmatic Functional Programming in the JS land with Clojurescript and Om
Pragmatic Functional Programming in the JS land with Clojurescript and OmPragmatic Functional Programming in the JS land with Clojurescript and Om
Pragmatic Functional Programming in the JS land with Clojurescript and Om
 
Building Single Page Apps with Backbone.js, Coffeescript and Rails 3.1
Building Single Page Apps with Backbone.js, Coffeescript and Rails 3.1Building Single Page Apps with Backbone.js, Coffeescript and Rails 3.1
Building Single Page Apps with Backbone.js, Coffeescript and Rails 3.1
 
Crystal - Statically Typed Ruby
Crystal - Statically Typed RubyCrystal - Statically Typed Ruby
Crystal - Statically Typed Ruby
 
Globalisation
GlobalisationGlobalisation
Globalisation
 
Building Single Page Apps with React.JS
Building Single Page Apps with React.JSBuilding Single Page Apps with React.JS
Building Single Page Apps with React.JS
 
Introduction to Rails
Introduction to RailsIntroduction to Rails
Introduction to Rails
 
a-beginners-guide-to-namas-web_final
a-beginners-guide-to-namas-web_finala-beginners-guide-to-namas-web_final
a-beginners-guide-to-namas-web_final
 
Ruby On Rails - 1. Ruby Introduction
Ruby On Rails - 1. Ruby IntroductionRuby On Rails - 1. Ruby Introduction
Ruby On Rails - 1. Ruby Introduction
 
Ruby on Rails Introduction | FEU-EAC, February 2014
Ruby on Rails Introduction | FEU-EAC, February 2014Ruby on Rails Introduction | FEU-EAC, February 2014
Ruby on Rails Introduction | FEU-EAC, February 2014
 
Rochester on Rails: Introduction to Ruby
Rochester on Rails: Introduction to RubyRochester on Rails: Introduction to Ruby
Rochester on Rails: Introduction to Ruby
 

Similaire à Ruby on Rails - Introduction

Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Railsrstankov
 
Phoenix for Rails Devs
Phoenix for Rails DevsPhoenix for Rails Devs
Phoenix for Rails DevsDiacode
 
Pourquoi ruby et rails déchirent
Pourquoi ruby et rails déchirentPourquoi ruby et rails déchirent
Pourquoi ruby et rails déchirentNicolas Ledez
 
RoR 101: Session 2
RoR 101: Session 2RoR 101: Session 2
RoR 101: Session 2Rory Gianni
 
Rails Engine | Modular application
Rails Engine | Modular applicationRails Engine | Modular application
Rails Engine | Modular applicationmirrec
 
Rails 3: Dashing to the Finish
Rails 3: Dashing to the FinishRails 3: Dashing to the Finish
Rails 3: Dashing to the FinishYehuda Katz
 
Ruby on Rails + AngularJS + Twitter Bootstrap
Ruby on Rails + AngularJS + Twitter BootstrapRuby on Rails + AngularJS + Twitter Bootstrap
Ruby on Rails + AngularJS + Twitter BootstrapMarcio Marinho
 
Learning to code for startup mvp session 3
Learning to code for startup mvp session 3Learning to code for startup mvp session 3
Learning to code for startup mvp session 3Henry S
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasminePaulo Ragonha
 
What's new and great in Rails 3 - Matt Gauger - Milwaukee Ruby Users Group De...
What's new and great in Rails 3 - Matt Gauger - Milwaukee Ruby Users Group De...What's new and great in Rails 3 - Matt Gauger - Milwaukee Ruby Users Group De...
What's new and great in Rails 3 - Matt Gauger - Milwaukee Ruby Users Group De...Matt Gauger
 
Ruby on Rails introduction
Ruby on Rails introduction Ruby on Rails introduction
Ruby on Rails introduction Tran Hung
 
Writing HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAEWriting HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAERon Reiter
 
Rails for Beginners - Le Wagon
Rails for Beginners - Le WagonRails for Beginners - Le Wagon
Rails for Beginners - Le WagonAlex Benoit
 
Rapid Prototyping FTW!!!
Rapid Prototyping FTW!!!Rapid Prototyping FTW!!!
Rapid Prototyping FTW!!!cloudbring
 
Connecting the Worlds of Java and Ruby with JRuby
Connecting the Worlds of Java and Ruby with JRubyConnecting the Worlds of Java and Ruby with JRuby
Connecting the Worlds of Java and Ruby with JRubyNick Sieger
 
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011Nick Sieger
 
Plug it on!... with railties
Plug it on!... with railtiesPlug it on!... with railties
Plug it on!... with railtiesrails.mx
 

Similaire à Ruby on Rails - Introduction (20)

Wider than rails
Wider than railsWider than rails
Wider than rails
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Rails
 
Phoenix for Rails Devs
Phoenix for Rails DevsPhoenix for Rails Devs
Phoenix for Rails Devs
 
Pourquoi ruby et rails déchirent
Pourquoi ruby et rails déchirentPourquoi ruby et rails déchirent
Pourquoi ruby et rails déchirent
 
RoR 101: Session 2
RoR 101: Session 2RoR 101: Session 2
RoR 101: Session 2
 
Rails Engine | Modular application
Rails Engine | Modular applicationRails Engine | Modular application
Rails Engine | Modular application
 
Rails 3: Dashing to the Finish
Rails 3: Dashing to the FinishRails 3: Dashing to the Finish
Rails 3: Dashing to the Finish
 
Ruby on Rails + AngularJS + Twitter Bootstrap
Ruby on Rails + AngularJS + Twitter BootstrapRuby on Rails + AngularJS + Twitter Bootstrap
Ruby on Rails + AngularJS + Twitter Bootstrap
 
Learning to code for startup mvp session 3
Learning to code for startup mvp session 3Learning to code for startup mvp session 3
Learning to code for startup mvp session 3
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
 
Dev streams2
Dev streams2Dev streams2
Dev streams2
 
What's new and great in Rails 3 - Matt Gauger - Milwaukee Ruby Users Group De...
What's new and great in Rails 3 - Matt Gauger - Milwaukee Ruby Users Group De...What's new and great in Rails 3 - Matt Gauger - Milwaukee Ruby Users Group De...
What's new and great in Rails 3 - Matt Gauger - Milwaukee Ruby Users Group De...
 
Play vs Rails
Play vs RailsPlay vs Rails
Play vs Rails
 
Ruby on Rails introduction
Ruby on Rails introduction Ruby on Rails introduction
Ruby on Rails introduction
 
Writing HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAEWriting HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAE
 
Rails for Beginners - Le Wagon
Rails for Beginners - Le WagonRails for Beginners - Le Wagon
Rails for Beginners - Le Wagon
 
Rapid Prototyping FTW!!!
Rapid Prototyping FTW!!!Rapid Prototyping FTW!!!
Rapid Prototyping FTW!!!
 
Connecting the Worlds of Java and Ruby with JRuby
Connecting the Worlds of Java and Ruby with JRubyConnecting the Worlds of Java and Ruby with JRuby
Connecting the Worlds of Java and Ruby with JRuby
 
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
 
Plug it on!... with railties
Plug it on!... with railtiesPlug it on!... with railties
Plug it on!... with railties
 

Dernier

Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbuapidays
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...apidays
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 

Dernier (20)

Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 

Ruby on Rails - Introduction

  • 1. Turbocharge your web development with Rails Vagmi Mudumbai Dharana Software Innovations Pvt Ltd @vagmi / vagmi@dharanasoft.com
  • 2. About me http://vagmim.com RailsPundit ChennaiGeeks facebook.com/groups/chennaigeeks
  • 4.
  • 5. Agenda • About Ruby • Controllers • About Rails • Layouts • MVC • Views • Models • Forms • Relationships • Q &A • Routes
  • 6. •Created by Yakuhiro “Matz” Matsumoto in 1995 in Japan •Generally available to the english speaking world at 2000
  • 7. •Multi paradigm language •Supports imperative/Object Oriented/ Functional styles of programming
  • 8. # The Greeter class class Greeter def initialize(name) @name = name.capitalize end def salute puts "Hello #{@name}!" end end # Create a new object g = Greeter.new("world") # Output "Hello World!" g.salute
  • 9. •Many Flavors •MRI/YARV •JRuby •Rubinius •IronRuby •Maglev •And more
  • 10. • Created in 2005 by David Heinemeier Hannson (a.k.a. DHH) • A web framework to helps you actually enjoy programming
  • 11. • Intended to be simple and consistent to use • Convention over configuration • Freedom from needless XML situps
  • 12. Installing Ruby • For windows you can get Ruby from • http://rubyinstaller.org/
  • 13. Installing Ruby • For Linux and Mac OSX • Install via RVM • http://rvm.beginrescueend.com/ • http://amerine.net/2010/02/24/rvm-rails3- ruby-1-9-2-setup.html
  • 14. Installing Rails $ gem install rails
  • 15. Rails MVC Router Controller View Model DB HTML/CSS/JS
  • 16. Create a Rails App $ rails new todolist
  • 17. Rails Project Structure myapp/ |-- Gemfile # all the dependencies go here |-- Rakefile # the build file?? |-- app # The entire application sits here |-- config # Configure the app to your heart's content |-- db # Database migrations, seed file |-- lib # Custom rake tasks and your libraries |-- log # The directory we all love |-- public # Static assets like CSS, JS and images |-- script # Contains one file "rails" |-- test # Tests - unit, functional, integration |-- tmp # misc stuff like sessions, pids and working files `-- vendor # 3rd party stuff - not used as much these days
  • 18. Rails Project Structure myapp/ `-- app |-- controllers # controllers | `-- application_controller.rb |-- helpers | `-- application_helper.rb # view helpers |-- mailers |-- models `-- views `-- layouts `-- application.html.erb # could be haml or any other # templating language
  • 19. Rails Project Structure myapp/ `-- config |-- application.rb # the main application config file |-- boot.rb # setup bundler and the environment |-- database.yml # setup database connections |-- environments | |-- development.rb # development specific setup | |-- production.rb # production specific setup | `-- test.rb # test specific setup |-- initializers | |-- inflections.rb # any file put inside | |-- mime_types.rb # this directory will | |-- secret_token.rb # be executed when the | `-- session_store.rb # rails application boots |-- locales | `-- en.yml # setup internationalization `-- routes.rb # map URLs to Controllers/Actions
  • 21. Create a model $ rails g model todo title:string done:boolean completed_at:datetime invoke active_record create db/migrate/20110625034305_create_todos.rb create app/models/todo.rb invoke test_unit create test/unit/todo_test.rb create test/fixtures/todos.yml
  • 22. class CreateTodos < ActiveRecord::Migration def self.up create_table :todos do |t| t.string :title t.boolean :done t.datetime :completed_at t.timestamps end end def self.down drop_table :todos end end Migration
  • 23. The model class class Todo < ActiveRecord::Base # seriously thats it # rails does rest of the magic end
  • 24. Create the table $ rake db:migrate (in /path/to/myapp) == CreateTodos: migrating ================ -- create_table(:todos) -> 0.0015s == CreateTodos: migrated (0.0016s) ===========================================
  • 25. $ rails console Loading development environment (Rails 3.0.7) ruby-1.9.2-p180 :001 > The Rails console The REPL for Rails
  • 26. > todo=Todo.new # => #<Todo id: nil, title: nil, done: nil, completed_at: nil, created_at: nil, updated_at: nil> > todo.title="Some title" # => "Some title" > todo.save # AREL (0.5ms) INSERT INTO "todos" ("title", "done", "completed_at", "created_at", "updated_at") VALUES ('Some title', NULL, NULL, '2011-06-25 04:21:47.272312', '2011-06-25 04:21:47.272312') => true Create a new object
  • 27. > todo = Todo.new(:title=>"Teach Rails",:done=>true,:completed_at=>Time.now) => #<Todo id: nil, title: "Teach Rails", done: true, completed_at: "2011-06-25 04:26:29", created_at: nil, updated_at: nil> > todo.save AREL (0.8ms) INSERT INTO "todos" ("title", "done", "completed_at", "created_at", "updated_at") VALUES ('Teach Rails', 't', '2011-06-25 04:26:29.853087', '2011-06-25 04:26:38.869335', '2011-06-25 04:26:38.869335') => true Create a new object
  • 28. Querying > Todo.where(:done=>true).all Todo Load (0.4ms) SELECT "todos".* FROM "todos" WHERE "todos"."done" = 't' => [#<Todo id: 2, title: "Teach Rails", done: true, completed_at: "2011-06-25 04:26:29", created_at: "2011-06-25 04:26:38", updated_at: "2011-06-25 04:26:38">]
  • 29. > t = Todo.where(:done=>true).first Todo Load (0.4ms) SELECT "todos".* FROM "todos" WHERE "todos"."done" = 't' LIMIT 1 => #<Todo id: 2, title: "Teach Rails", done: true, completed_at: "2011-06-25 04:26:29", created_at: "2011-06-25 04:26:38", updated_at: "2011-06-25 04:26:38"> > t.done=false => false > t.save AREL (0.5ms) UPDATE "todos" SET "done" = 'f', "updated_at" = '2011-06-25 05:31:07.025845' WHERE "todos"."id" = 2 => true Update object
  • 30. Deleting objects > t.destroy AREL (0.5ms) DELETE FROM "todos" WHERE "todos"."id" = 2 => #<Todo id: 2, title: "Teach Rails", done: false, completed_at: "2011-06-25 04:26:29", created_at: "2011-06-25 04:26:38", updated_at: "2011-06-25 05:31:07">
  • 31. Relationships $ rails g bucket name:string $ rails g task title:string done:boolean bucket:references create_table :buckets do |t| class Bucket < ActiveRecord::Base t.string :name has_many :tasks t.timestamps end end create_table :tasks do |t| t.string :title class Task < ActiveRecord::Base t.boolean :done belongs_to :bucket t.references :bucket end t.timestamps end
  • 32. Creating and querying relationships > bucket = Bucket.create(:name=>"work") # create work bucket > bucket.tasks.create(:title=>"Fill in timesheets") # create task under bucket > bucket.tasks.create(:title=>"Fix bug #234") #create another task > bucket.tasks.count # => 2 > bucket.tasks > t=Task.first # get the task object > t.bucket # access the bucket object from the task object
  • 35. config/routes.rb Myapp::Application.routes.draw do # direct root (/) to WelcomeController's # index action root :to => "welcome#index" end $ rails g controller welcome
  • 36. Welcome Controller # app/controllers/welcome_controller.rb class WelcomeController < ApplicationController def index render :text=>"hello world" end end
  • 37. Views # app/controller/welcome_controller.rb class WelcomeController < ApplicationController def index @time = Time.now end end <!-- in app/views/welcome/index.html.erb --> <h1>The time is <%=@time.strftime('%d-%b-%Y %H:%M: %S')%></h1>
  • 38. ReST and Resources Myapp::Application.routes.draw do resources :tasks end $ rake routes (in /path/to/myapp) tasks GET /tasks(.:format) {:action=>"index", :controller=>"tasks"} POST /tasks(.:format) {:action=>"create", :controller=>"tasks"} new_task GET /tasks/new(.:format) {:action=>"new", :controller=>"tasks"} edit_task GET /tasks/:id/edit(.:format) {:action=>"edit", :controller=>"tasks"} task GET /tasks/:id(.:format) {:action=>"show", :controller=>"tasks"} PUT /tasks/:id(.:format) {:action=>"update", :controller=>"tasks"} DELETE /tasks/:id(.:format) {:action=>"destroy", :controller=>"tasks"}
  • 39. ReST and Resources class TasksController < ApplicationController # index displays a list of tasks # new presents a form to create a task # create processes the form submitted by the new action # show displays an individual task # edit presents a form to update a task # update processes the form submitted by the edit action # destroy deletes a task end
  • 40. Nested resources Myapp::Application.routes.draw do resources :buckets, :shallow=>true do resources :tasks end end $ rake routes (in /path/to/myapp) bucket_tasks GET /buckets/:bucket_id/tasks(.:format) {:action=>"index", :controller=>"tasks"} POST /buckets/:bucket_id/tasks(.:format) {:action=>"create", :controller=>"tasks"} new_bucket_task GET /buckets/:bucket_id/tasks/new(.:format) {:action=>"new", :controller=>"tasks"} edit_task GET /tasks/:id/edit(.:format) {:action=>"edit", :controller=>"tasks"} task GET /tasks/:id(.:format) {:action=>"show", :controller=>"tasks"} PUT /tasks/:id(.:format) {:action=>"update", :controller=>"tasks"} DELETE /tasks/:id(.:format) {:action=>"destroy", :controller=>"tasks"} buckets GET /buckets(.:format) {:action=>"index", :controller=>"buckets"} POST /buckets(.:format) {:action=>"create", :controller=>"buckets"} new_bucket GET /buckets/new(.:format) {:action=>"new", :controller=>"buckets"} edit_bucket GET /buckets/:id/edit(.:format) {:action=>"edit", :controller=>"buckets"} bucket GET /buckets/:id(.:format) {:action=>"show", :controller=>"buckets"} PUT /buckets/:id(.:format) {:action=>"update", :controller=>"buckets"} DELETE /buckets/:id(.:format) {:action=>"destroy", :controller=>"buckets"} * If you squint hard enough, you will be able to read it.
  • 41. BucketsController def index @buckets = Bucket.all end def show @bucket=Bucket.find(params[:id]) end def destroy @bucket=Bucket.find(params[:id]) @bucket.destroy redirect_to buckets_path end
  • 42. BucketsController def new @bucket = Bucket.new end def create @bucket = Bucket.new(params[:bucket]) if(@bucket.save) flash[:notice] = "Bucket created" redirect_to @bucket else render :action=>:new end end
  • 43. BucketsController def edit @bucket = Bucket.find(params[:id]) end def update @bucket=Bucket.find(params[:id]) if(@bucket.update_attributes(params[:bucket])) flash[:notice]="Bucket updated" redirect_to @bucket else render :action=>:edit end end
  • 44. Tasks Controller def new @bucket = Bucket.find(params[:bucket_id]) @task = @bucket.tasks.build end def create @bucket = Bucket.find(params[:bucket_id]) # the form should have passed bucket_id # as one of the parameters via # a hidden field @task = Task.new(params[:task]) if(@task.save) flash[:notice]="task created" redirect_to @task else render :action=>:new end end The other actions remain the same
  • 46. Formtastic # add these to your # Gemfile gem 'formtastic' gem 'jquery-rails' $ rails g formtastic:install $ rails g jquery:install <!-- in app/views/buckets/new.html.erb --> <%= semantic_form_for @bucket do |f| %> <%= f.inputs %> <%= f.buttons %> <% end %>
  • 48. Vagmi Mudumbai vagmi@dharanasoft.com twitter.com/vagmi facebook.com/vagmi linkedin.com/in/vagmi github.com/vagmi plus.google.com/ 106483555843485143380/ Thank you