SlideShare uma empresa Scribd logo
1 de 23
Rails
Beginners Guide
Rails
• Web application framework written in ruby
• Based on Model View Controller architecture (MVC)
• Uses core APIs and generators to
    – reduce the coding burden and
    – focus your efforts on value-adding development
• Large community of developers
    – Provide support to each other
    – Write gems (libraries) to extend the framework (see
      rubygems.org)




6/16/2011                                          2
Why Rails
• Productive
    – Programming in Ruby is simpler
    – Boiler plate already in place (e.g. binding objects between
      tiers)
    – Gems for re-usable features
• Each to understand
    – Convention over configuration
    – Configuration-like programming e.g. ActiveRecord
• Large community
• Matur(e/ing)




6/16/2011                                           3
Setup
Getting your environment ready
Install
• MySQL 5.X
• HeidiSQL (SQL Client)
• Ruby 1.8.7
    – http://www.ruby-lang.org/en/downloads/
    – Note version
• Rails
    – gem install rails –v=2.3.5




6/16/2011 Nokia Music                          5
Project Setup
• Create a database
    – mysql –u root -p

    – create database library;
    – GRANT ALL ON library.* TO ‘library’@’localhost’ IDENTIFIED
      BY ‘library ‘;
    – FLUSH PRIVILEGES;


• Create a rails application
    – rails library




6/16/2011 Nokia Music                             6
Project Setup
• Configure your application to communicate to the
  database
    – config/database.yml
        • development:
        • adapter: mysql
        • database: library
        • username: library
        • password: library
        • host: localhost




6/16/2011 Nokia Music                      7
Concepts
High-level Overview
Concepts
•   Rake
•   Routes
•   Migrations
•   Generators
•   Object relationships
•   Validates




6/16/2011 Nokia Music      9
Rake
• Rake is ruby’s build program (similar to make and ant)
• Rake uses rakefiles to manage the build
    – Written in ruby
    – Default one created for rails which includes standard tasks
• Rake tasks are namespaced
• To see all the available rake tasks run rake –T or rake –
  tasks
• Most commonly used rake tasks
    – rake db:migrate – migrate the database to the current
      version
    – rake db:rollback – move the database back a version
    – rake test – run all tests (unit tests and functional tests)


6/16/2011                                              10
Routes
• The rails router matches incoming requests to
  controller actions
• Routes are configured in config/routes.rb
• Some generators add routes e.g. ruby script/generate
  scaffold cd name:string artist:string genre:string
    – Will add routes to add, delete, update, show, list posts
• Routes can also be used to generate URLs for links,
  forms e.g.
    – link_to @cd.name, cd_path(@cd) – creates a link to the post
      show page
• The routes API supports a multitude of operations, a
  common ones is:
    – map.resources :cds – creates CRUDL routes

6/16/2011                                            11
Migrations
• Migrations allow you to manage a database through
  versions
• Each version is held in a separate timestamp prefixed
  file in db/migrate
• Each migration knows how to update the database
  (self.up) and how to rollback (self.down)
• Migrations are written in ruby and the migrations api
  supports a wide range of table and column alterations
• You can also run normal SQL and ruby code
• Every time a migration is run the <table> table is
  updated to include the timestamp
• Migrations with rake db:migrate and rake db:rollback


6/16/2011                                  12
Generators
• Command line interface to run code generators
• Rails comes with a set of out of the box templates
    – You can customise these
    – You can add your own
• Typically generate classes into your app directory e.g.
    – ruby script/generate model cd name:string artist:string
      genre:string – generates a model and associated files (tests,
      migrations) with the attributes specified
    – ruby script/generate scaffold cd name:string artist:string
      genre:string - creates not only the model but also a CRUDL
      controller and views
    – ruby script/generate migration add_record_label_to_cd –
      creates a single migration


6/16/2011                                           13
Object relationships
• ActiveRecord is ruby implementation of the active
  record pattern (Martin Fowler 2003)
• Set of meta-programming methods allow you to
  configure relationships in your model objects:
    – belongs_to :cd - for table holding pkey
    – has_many :tracks - notice the plural, for connected table
    – has_many :genres, :through => :cd_genres – to link
      through a relationship table
•   Then you can call methods on your model objects e.g.
•   @cd.tracks # array of tracks
•   @cd.genres # array of genres
•   @track.cd # cd model object


6/16/2011                                           14
Validations
• Rails makes a set of validation methods available
• Configure them in your model object
• Rails validates on save and stores and saves it in
  <object>.errors
• Some examples:
    – validates_presence_of :title, :artist – mandatory field checks
    – validates_uniqueness_of :title – each title can only be used
      once
    – validates_numericality_of :quantity – must be a number




6/16/2011                                            15
Console
• Console lets you run your application through the
  command line and test out pieces of code
• To start a console session
    – ruby script/console
• From there you can run ruby commands and will have
  access to all of your objects
• The console saves a lot of time loading and reloading
  web pages to test functionality
• Some useful commands
    – _ - provides access to the last result e.g. @cd = _
    – puts @cd.to_yaml (or y @cd) – writes out an indented
      version of the object
    – reload! – reload the app
    – <tab> - autocompletes methods

6/16/2011                                         16
Simple Project
A CD library
Create your model and scaffold
• rails library
• cd library
• ruby script/generate scaffold cd name:string
  artist:string genre:string
• rake db:migrate
• ruby script/server

• http://localhost:3000/cds




6/16/2011                                  18
Create relationships between models
• ruby script/generate scaffold track name:string
  cd_id:integer
• rake db:migrate
• Create associations in the model classes
    – track.rb - belongs_to :cd
    – cd.rb - has_many :track
• Allow tracks to select an album in track/edit.html.erb
    – <%= select( “track", “cd_id", Cd.all.map {|cd| [cd.name,
      cd.id]}, { :include_blank => "No part of an album" }, {:class
      => "fieldSelect"}) %>




6/16/2011                                          19
Next
Where to go next
Taking a step beyond the basics
• Access other people’s shared code via gems and plugins
    – authlogic – controllers and UI to enable authentication
    – will_paginate – rich pagination for lists
    – cucumber – behaviour driven testing
    – faker – data generator
    – paperclip – file attachments
• Caching – Rails.cache.read/write/delete and config for
  cache setup
• Deployment with capistrano
• Ajax via jQuery and format.js




6/16/2011                                           21
References
Useful links
Further reading and videos
• Railscasts – http://www.railscasts.com
    – Video tutorials from Ryan Bates
• Pivotal Labs - http://pivotallabs.com/talks
    – Wide range of talks including rails from leading tech company
• has_many :through blog -
  http://blog.hasmanythrough.com/
    – John Susser’s blog, senior rails developer at Pivotal Labs
• Ruby Doc - http://www.ruby-doc.org/
    – Ruby class documentation




6/16/2011                                            23

Mais conteúdo relacionado

Mais procurados

Laravel introduction
Laravel introductionLaravel introduction
Laravel introductionSimon Funk
 
Security Goodness with Ruby on Rails
Security Goodness with Ruby on RailsSecurity Goodness with Ruby on Rails
Security Goodness with Ruby on RailsSource Conference
 
Version control with subversion
Version control with subversionVersion control with subversion
Version control with subversionxprayc
 
Display earthquakes with Akka-http
Display earthquakes with Akka-httpDisplay earthquakes with Akka-http
Display earthquakes with Akka-httpPierangelo Cecchetto
 
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory CourseRuby on Rails 101 - Presentation Slides for a Five Day Introductory Course
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Coursepeter_marklund
 
Database Migrations with Gradle and Liquibase
Database Migrations with Gradle and LiquibaseDatabase Migrations with Gradle and Liquibase
Database Migrations with Gradle and LiquibaseDan Stine
 
Chef, Vagrant and Friends
Chef, Vagrant and FriendsChef, Vagrant and Friends
Chef, Vagrant and FriendsBen McRae
 
What's new in MySQL 5.5? FOSDEM 2011
What's new in MySQL 5.5? FOSDEM 2011What's new in MySQL 5.5? FOSDEM 2011
What's new in MySQL 5.5? FOSDEM 2011Lenz Grimmer
 
FITC - Here Be Dragons: Advanced JavaScript Debugging
FITC - Here Be Dragons: Advanced JavaScript DebuggingFITC - Here Be Dragons: Advanced JavaScript Debugging
FITC - Here Be Dragons: Advanced JavaScript DebuggingRami Sayar
 
Memphis php 01 22-13 - laravel basics
Memphis php 01 22-13 - laravel basicsMemphis php 01 22-13 - laravel basics
Memphis php 01 22-13 - laravel basicsJoe Ferguson
 
Rupy2012 ArangoDB Workshop Part2
Rupy2012 ArangoDB Workshop Part2Rupy2012 ArangoDB Workshop Part2
Rupy2012 ArangoDB Workshop Part2ArangoDB Database
 
Ruby on Rails : 簡介與入門
Ruby on Rails : 簡介與入門Ruby on Rails : 簡介與入門
Ruby on Rails : 簡介與入門Wen-Tien Chang
 
Develop realtime web with Scala and Xitrum
Develop realtime web with Scala and XitrumDevelop realtime web with Scala and Xitrum
Develop realtime web with Scala and XitrumNgoc Dao
 
Web Development with Laravel 5
Web Development with Laravel 5Web Development with Laravel 5
Web Development with Laravel 5Soheil Khodayari
 

Mais procurados (20)

Laravel introduction
Laravel introductionLaravel introduction
Laravel introduction
 
Security Goodness with Ruby on Rails
Security Goodness with Ruby on RailsSecurity Goodness with Ruby on Rails
Security Goodness with Ruby on Rails
 
Version control with subversion
Version control with subversionVersion control with subversion
Version control with subversion
 
Mini Training Flyway
Mini Training FlywayMini Training Flyway
Mini Training Flyway
 
Display earthquakes with Akka-http
Display earthquakes with Akka-httpDisplay earthquakes with Akka-http
Display earthquakes with Akka-http
 
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory CourseRuby on Rails 101 - Presentation Slides for a Five Day Introductory Course
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
 
Database Migrations with Gradle and Liquibase
Database Migrations with Gradle and LiquibaseDatabase Migrations with Gradle and Liquibase
Database Migrations with Gradle and Liquibase
 
Chef, Vagrant and Friends
Chef, Vagrant and FriendsChef, Vagrant and Friends
Chef, Vagrant and Friends
 
What's new in MySQL 5.5? FOSDEM 2011
What's new in MySQL 5.5? FOSDEM 2011What's new in MySQL 5.5? FOSDEM 2011
What's new in MySQL 5.5? FOSDEM 2011
 
FITC - Here Be Dragons: Advanced JavaScript Debugging
FITC - Here Be Dragons: Advanced JavaScript DebuggingFITC - Here Be Dragons: Advanced JavaScript Debugging
FITC - Here Be Dragons: Advanced JavaScript Debugging
 
Dockerize All The Things
Dockerize All The ThingsDockerize All The Things
Dockerize All The Things
 
Laravel
LaravelLaravel
Laravel
 
Apache spark
Apache sparkApache spark
Apache spark
 
Flywaydb
FlywaydbFlywaydb
Flywaydb
 
Memphis php 01 22-13 - laravel basics
Memphis php 01 22-13 - laravel basicsMemphis php 01 22-13 - laravel basics
Memphis php 01 22-13 - laravel basics
 
Rupy2012 ArangoDB Workshop Part2
Rupy2012 ArangoDB Workshop Part2Rupy2012 ArangoDB Workshop Part2
Rupy2012 ArangoDB Workshop Part2
 
Ruby on Rails : 簡介與入門
Ruby on Rails : 簡介與入門Ruby on Rails : 簡介與入門
Ruby on Rails : 簡介與入門
 
Develop realtime web with Scala and Xitrum
Develop realtime web with Scala and XitrumDevelop realtime web with Scala and Xitrum
Develop realtime web with Scala and Xitrum
 
Flyway
FlywayFlyway
Flyway
 
Web Development with Laravel 5
Web Development with Laravel 5Web Development with Laravel 5
Web Development with Laravel 5
 

Semelhante a Rails - getting started

Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Railsiradarji
 
Jasig rubyon rails
Jasig rubyon railsJasig rubyon rails
Jasig rubyon rails_zaMmer_
 
Jasig rubyon rails
Jasig rubyon railsJasig rubyon rails
Jasig rubyon rails_zaMmer_
 
Real time Analytics with Apache Kafka and Apache Spark
Real time Analytics with Apache Kafka and Apache SparkReal time Analytics with Apache Kafka and Apache Spark
Real time Analytics with Apache Kafka and Apache SparkRahul Jain
 
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
 
Ruby on-rails-101-presentation-slides-for-a-five-day-introductory-course-1194...
Ruby on-rails-101-presentation-slides-for-a-five-day-introductory-course-1194...Ruby on-rails-101-presentation-slides-for-a-five-day-introductory-course-1194...
Ruby on-rails-101-presentation-slides-for-a-five-day-introductory-course-1194...Nilesh Panchal
 
How To Install Ruby on Rails on Ubuntu
How To Install Ruby on Rails on UbuntuHow To Install Ruby on Rails on Ubuntu
How To Install Ruby on Rails on UbuntuVEXXHOST Private Cloud
 
Lecture #5 Introduction to rails
Lecture #5 Introduction to railsLecture #5 Introduction to rails
Lecture #5 Introduction to railsEvgeniy Hinyuk
 
Introduction to Rails by Evgeniy Hinyuk
Introduction to Rails by Evgeniy HinyukIntroduction to Rails by Evgeniy Hinyuk
Introduction to Rails by Evgeniy HinyukPivorak MeetUp
 
EWD 3 Training Course Part 1: How Node.js Integrates With Global Storage Data...
EWD 3 Training Course Part 1: How Node.js Integrates With Global Storage Data...EWD 3 Training Course Part 1: How Node.js Integrates With Global Storage Data...
EWD 3 Training Course Part 1: How Node.js Integrates With Global Storage Data...Rob Tweed
 
Programming the Semantic Web
Programming the Semantic WebProgramming the Semantic Web
Programming the Semantic WebLuigi De Russis
 
Kafka for Microservices – You absolutely need Avro Schemas! | Gerardo Gutierr...
Kafka for Microservices – You absolutely need Avro Schemas! | Gerardo Gutierr...Kafka for Microservices – You absolutely need Avro Schemas! | Gerardo Gutierr...
Kafka for Microservices – You absolutely need Avro Schemas! | Gerardo Gutierr...HostedbyConfluent
 
Ruby on Rails : First Mile
Ruby on Rails : First MileRuby on Rails : First Mile
Ruby on Rails : First MileGourab Mitra
 
Michael stack -the state of apache h base
Michael stack -the state of apache h baseMichael stack -the state of apache h base
Michael stack -the state of apache h basehdhappy001
 

Semelhante a Rails - getting started (20)

Supa fast Ruby + Rails
Supa fast Ruby + RailsSupa fast Ruby + Rails
Supa fast Ruby + Rails
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Rails
 
Aspose pdf
Aspose pdfAspose pdf
Aspose pdf
 
Jasig rubyon rails
Jasig rubyon railsJasig rubyon rails
Jasig rubyon rails
 
Jasig rubyon rails
Jasig rubyon railsJasig rubyon rails
Jasig rubyon rails
 
Real time Analytics with Apache Kafka and Apache Spark
Real time Analytics with Apache Kafka and Apache SparkReal time Analytics with Apache Kafka and Apache Spark
Real time Analytics with Apache Kafka and Apache Spark
 
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
 
12 Introduction to Rails
12 Introduction to Rails12 Introduction to Rails
12 Introduction to Rails
 
Ruby on-rails-101-presentation-slides-for-a-five-day-introductory-course-1194...
Ruby on-rails-101-presentation-slides-for-a-five-day-introductory-course-1194...Ruby on-rails-101-presentation-slides-for-a-five-day-introductory-course-1194...
Ruby on-rails-101-presentation-slides-for-a-five-day-introductory-course-1194...
 
How To Install Ruby on Rails on Ubuntu
How To Install Ruby on Rails on UbuntuHow To Install Ruby on Rails on Ubuntu
How To Install Ruby on Rails on Ubuntu
 
Short-Training asp.net vNext
Short-Training asp.net vNextShort-Training asp.net vNext
Short-Training asp.net vNext
 
Ruby on rails
Ruby on railsRuby on rails
Ruby on rails
 
Lecture #5 Introduction to rails
Lecture #5 Introduction to railsLecture #5 Introduction to rails
Lecture #5 Introduction to rails
 
Introduction to Rails by Evgeniy Hinyuk
Introduction to Rails by Evgeniy HinyukIntroduction to Rails by Evgeniy Hinyuk
Introduction to Rails by Evgeniy Hinyuk
 
EWD 3 Training Course Part 1: How Node.js Integrates With Global Storage Data...
EWD 3 Training Course Part 1: How Node.js Integrates With Global Storage Data...EWD 3 Training Course Part 1: How Node.js Integrates With Global Storage Data...
EWD 3 Training Course Part 1: How Node.js Integrates With Global Storage Data...
 
Programming the Semantic Web
Programming the Semantic WebProgramming the Semantic Web
Programming the Semantic Web
 
Kafka for Microservices – You absolutely need Avro Schemas! | Gerardo Gutierr...
Kafka for Microservices – You absolutely need Avro Schemas! | Gerardo Gutierr...Kafka for Microservices – You absolutely need Avro Schemas! | Gerardo Gutierr...
Kafka for Microservices – You absolutely need Avro Schemas! | Gerardo Gutierr...
 
Ruby on Rails : First Mile
Ruby on Rails : First MileRuby on Rails : First Mile
Ruby on Rails : First Mile
 
Ruby and Security
Ruby and SecurityRuby and Security
Ruby and Security
 
Michael stack -the state of apache h base
Michael stack -the state of apache h baseMichael stack -the state of apache h base
Michael stack -the state of apache h base
 

Último

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
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
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
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
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
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
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024SynarionITSolutions
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 

Último (20)

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
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
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
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...
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
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
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 

Rails - getting started

  • 2. Rails • Web application framework written in ruby • Based on Model View Controller architecture (MVC) • Uses core APIs and generators to – reduce the coding burden and – focus your efforts on value-adding development • Large community of developers – Provide support to each other – Write gems (libraries) to extend the framework (see rubygems.org) 6/16/2011 2
  • 3. Why Rails • Productive – Programming in Ruby is simpler – Boiler plate already in place (e.g. binding objects between tiers) – Gems for re-usable features • Each to understand – Convention over configuration – Configuration-like programming e.g. ActiveRecord • Large community • Matur(e/ing) 6/16/2011 3
  • 5. Install • MySQL 5.X • HeidiSQL (SQL Client) • Ruby 1.8.7 – http://www.ruby-lang.org/en/downloads/ – Note version • Rails – gem install rails –v=2.3.5 6/16/2011 Nokia Music 5
  • 6. Project Setup • Create a database – mysql –u root -p – create database library; – GRANT ALL ON library.* TO ‘library’@’localhost’ IDENTIFIED BY ‘library ‘; – FLUSH PRIVILEGES; • Create a rails application – rails library 6/16/2011 Nokia Music 6
  • 7. Project Setup • Configure your application to communicate to the database – config/database.yml • development: • adapter: mysql • database: library • username: library • password: library • host: localhost 6/16/2011 Nokia Music 7
  • 9. Concepts • Rake • Routes • Migrations • Generators • Object relationships • Validates 6/16/2011 Nokia Music 9
  • 10. Rake • Rake is ruby’s build program (similar to make and ant) • Rake uses rakefiles to manage the build – Written in ruby – Default one created for rails which includes standard tasks • Rake tasks are namespaced • To see all the available rake tasks run rake –T or rake – tasks • Most commonly used rake tasks – rake db:migrate – migrate the database to the current version – rake db:rollback – move the database back a version – rake test – run all tests (unit tests and functional tests) 6/16/2011 10
  • 11. Routes • The rails router matches incoming requests to controller actions • Routes are configured in config/routes.rb • Some generators add routes e.g. ruby script/generate scaffold cd name:string artist:string genre:string – Will add routes to add, delete, update, show, list posts • Routes can also be used to generate URLs for links, forms e.g. – link_to @cd.name, cd_path(@cd) – creates a link to the post show page • The routes API supports a multitude of operations, a common ones is: – map.resources :cds – creates CRUDL routes 6/16/2011 11
  • 12. Migrations • Migrations allow you to manage a database through versions • Each version is held in a separate timestamp prefixed file in db/migrate • Each migration knows how to update the database (self.up) and how to rollback (self.down) • Migrations are written in ruby and the migrations api supports a wide range of table and column alterations • You can also run normal SQL and ruby code • Every time a migration is run the <table> table is updated to include the timestamp • Migrations with rake db:migrate and rake db:rollback 6/16/2011 12
  • 13. Generators • Command line interface to run code generators • Rails comes with a set of out of the box templates – You can customise these – You can add your own • Typically generate classes into your app directory e.g. – ruby script/generate model cd name:string artist:string genre:string – generates a model and associated files (tests, migrations) with the attributes specified – ruby script/generate scaffold cd name:string artist:string genre:string - creates not only the model but also a CRUDL controller and views – ruby script/generate migration add_record_label_to_cd – creates a single migration 6/16/2011 13
  • 14. Object relationships • ActiveRecord is ruby implementation of the active record pattern (Martin Fowler 2003) • Set of meta-programming methods allow you to configure relationships in your model objects: – belongs_to :cd - for table holding pkey – has_many :tracks - notice the plural, for connected table – has_many :genres, :through => :cd_genres – to link through a relationship table • Then you can call methods on your model objects e.g. • @cd.tracks # array of tracks • @cd.genres # array of genres • @track.cd # cd model object 6/16/2011 14
  • 15. Validations • Rails makes a set of validation methods available • Configure them in your model object • Rails validates on save and stores and saves it in <object>.errors • Some examples: – validates_presence_of :title, :artist – mandatory field checks – validates_uniqueness_of :title – each title can only be used once – validates_numericality_of :quantity – must be a number 6/16/2011 15
  • 16. Console • Console lets you run your application through the command line and test out pieces of code • To start a console session – ruby script/console • From there you can run ruby commands and will have access to all of your objects • The console saves a lot of time loading and reloading web pages to test functionality • Some useful commands – _ - provides access to the last result e.g. @cd = _ – puts @cd.to_yaml (or y @cd) – writes out an indented version of the object – reload! – reload the app – <tab> - autocompletes methods 6/16/2011 16
  • 18. Create your model and scaffold • rails library • cd library • ruby script/generate scaffold cd name:string artist:string genre:string • rake db:migrate • ruby script/server • http://localhost:3000/cds 6/16/2011 18
  • 19. Create relationships between models • ruby script/generate scaffold track name:string cd_id:integer • rake db:migrate • Create associations in the model classes – track.rb - belongs_to :cd – cd.rb - has_many :track • Allow tracks to select an album in track/edit.html.erb – <%= select( “track", “cd_id", Cd.all.map {|cd| [cd.name, cd.id]}, { :include_blank => "No part of an album" }, {:class => "fieldSelect"}) %> 6/16/2011 19
  • 21. Taking a step beyond the basics • Access other people’s shared code via gems and plugins – authlogic – controllers and UI to enable authentication – will_paginate – rich pagination for lists – cucumber – behaviour driven testing – faker – data generator – paperclip – file attachments • Caching – Rails.cache.read/write/delete and config for cache setup • Deployment with capistrano • Ajax via jQuery and format.js 6/16/2011 21
  • 23. Further reading and videos • Railscasts – http://www.railscasts.com – Video tutorials from Ryan Bates • Pivotal Labs - http://pivotallabs.com/talks – Wide range of talks including rails from leading tech company • has_many :through blog - http://blog.hasmanythrough.com/ – John Susser’s blog, senior rails developer at Pivotal Labs • Ruby Doc - http://www.ruby-doc.org/ – Ruby class documentation 6/16/2011 23