SlideShare a Scribd company logo
1 of 69
Download to read offline
Ruby On Rails
                         Intro & Tutorial

                             Mason Chang




Saturday, April 13, 13
Who I am?

                         • Mason Chang (張銘軒)
                         • Works at OptimisDev
                         • twitter: @changmason
                         • github: https://github.com/changmason

Saturday, April 13, 13
Part I



Saturday, April 13, 13
What is Rails?



Saturday, April 13, 13
Rails is...




                           http://rubyonrails.org/

Saturday, April 13, 13
Rails is...

                         • Created by DHH of 37signals in 2004
                         • Extracted from product Basecamp
                         • Of course, written in Ruby


Saturday, April 13, 13
Rails Philosophy



Saturday, April 13, 13
Don't Repeat Yourself


                         • Code generators
                         • Rake tasks
                         • Extentions

Saturday, April 13, 13
Code generators

                         • Generate new project
                         • Generate models
                         • Generate controllers & views


Saturday, April 13, 13
Rake tasks

                         • Run tests
                         • Manipulate database
                         • Show useful info

Saturday, April 13, 13
Extensions

                         • Sensible core extensions
                         • Helper methods
                         • A lot of 3rd party gems


Saturday, April 13, 13
Convention over
                             Configuration(1)

                         • Convention for environments
                            development, test and production
                         • Convention for organizing code
                         • Convention for organizing assets

Saturday, April 13, 13
Convention over
                             Configuration(2)

                         • Convention for models
                            model names - table names
                            model attributes - record fields
                         • Convention for controllers & views
                            controller actions - view templates


Saturday, April 13, 13
MVC Architecture



Saturday, April 13, 13
http://betterexplained.com/articles/intermediate-rails-understanding-models-views-and-controllers/

Saturday, April 13, 13
RESTful Routes



Saturday, April 13, 13
Combine HTTP verb and path to
                         dispatch requests to corresponding
                                  handlers (actions)




                                 http://guides.rubyonrails.org/routing.html

Saturday, April 13, 13
A very simple blog
                            in 5 minute


Saturday, April 13, 13
Part II



Saturday, April 13, 13
ActiveRecord & Model



Saturday, April 13, 13
What is ActiveRecord?

                         • ORM, Object-Relational Mapping
                         • Dealing with SQL
                         • A standalone Module
                         • Tons of functionalities

Saturday, April 13, 13
$ gem install activerecord
                         $ irb

                         > require 'rubygems'
                         > require 'active_record'
                         > ActiveRecord::VERSION::STRING




Saturday, April 13, 13
ActiveRecord can
                     connect to existing DB
                         > ActiveRecord::Base.establish_connection(
                             :adapter => 'mysql2',
                             :database => 'fju_test_db',
                             :username => 'root',
                             :password => '******' )

                         > ActiveRecord::Base.connection

                         > ActiveRecord::Base.connected?




Saturday, April 13, 13
ActiveRecord can
                          migrate existing DB
                         > ARConnection = AR::Base.connection

                         > ARConnection.create_table(:users) do |t|
                             t.string :name
                             t.integer :age
                             t.timestamps
                           end

                         > ARConnection.add_index(:users, 'name')




Saturday, April 13, 13
ActiveRecord can
                            execute raw SQL
                         > ARConnection = AR::Base.connection

                         > ARConnection.execute(%q{
                              INSERT INTO users (name, age)
                                VALUES ('Mason Chang', 30)
                           })

                         > resultes = ARConnection.execute(%q{
                              SELECT * FROM users WHERE age = 30
                           })
                         > results.fields
                         > results.first




Saturday, April 13, 13
User Model

                         > class User < ActiveRecord::Base
                           end

                         > require 'logger'

                         > ActiveRecord::Base.logger =
                             Logger.new(STDOUT)




Saturday, April 13, 13
Model can create
                                records
                         > user.newser = User.new(
                             :name => 'Eddie Kao', :age => 20)
                         > user.save


                         > User.create(
                             :name => 'Ryudo Teng', :age => 20)




Saturday, April 13, 13
Model can retrieve
                              records
                         > User.first

                         > User.last

                         > User.all

                         > User.find(1)

                         > User.find([1,2,3])

                         > User.find(:first,
                             :conditions => {:name => 'Eddie Kao'})

                         > User.find(:all,
                             :conditions => ['age < ?', 30])



Saturday, April 13, 13
Model can update
                               records
                         > user = User.find_by_name('Mason Chang')
                         > user.age = 10
                         > user.save

                         > user.update_attribute(:age, 20)

                         > user.update_attributes(
                             :name => 'Ming-hsuan Chang'
                             :age => 30)

                         > User.update(1, :age => 40)

                         > User.update_all(
                             {:age => 50}, ['age >= ?', 20])


Saturday, April 13, 13
Model can delete
                                records
                         > user = User.first

                         > user.delete # callbacks ignored

                         > user.destroy # callbacks triggered


                         > User.delete(1) # callbacks ignored

                         > User.destroy(1) # callbacks triggered




Saturday, April 13, 13
Model can do
                                    validations
                         > class User
                             validates_presence_of :name
                             validates_numericality_of :age
                           end


                         > user = User.new(:age => 'thirty")

                         > user.save # fail

                         > user.errors.messages




                             http://guides.rubyonrails.org/active_record_validations_callbacks.html

Saturday, April 13, 13
Model can have
                                   callbacks
                         • Callbacks are operations which hooked
                           into the lifecycle of an ActiveRecord object
                         • Object's lifecycle includes:
                             creating, updating and destroying an object
                             after initializing and finding an object



                               http://guides.rubyonrails.org/active_record_validations_callbacks.html

Saturday, April 13, 13
Callbacks for creating
                               an object
                         •   before_validation

                         •   after_validation

                         •   before_save

                         •   around_save

                         •   before_create

                         •   around_create

                         •   after_create

                         •   after_save



Saturday, April 13, 13
Callbacks for updating
                               an object
                         •   before_validation

                         •   after_validation

                         •   before_save

                         •   around_save

                         •   before_update

                         •   around_update

                         •   after_update

                         •   after_save



Saturday, April 13, 13
Callbacks for
                             destroying an object

                         •   before_destroy

                         •   around_destroy

                         •   after_destroy




Saturday, April 13, 13
Model can have
                               associations
                         • One-to-one
                         • One-to-many
                         • Many-to-many
                         • and more...

                                 http://guides.rubyonrails.org/association_basics.html

Saturday, April 13, 13
One-to-one association




Saturday, April 13, 13
One-to-many
                          association




Saturday, April 13, 13
Many-to-many
                          association




Saturday, April 13, 13
Part III



Saturday, April 13, 13
Task 0: Install Rails



Saturday, April 13, 13
$ gem install rails

                         $ rails --version




Saturday, April 13, 13
The rails command
                         • create new project
                            > rails new [project_name]

                         • start server
                            > rails server

                         • start console
                             > rails console

                         • execute generator
                            > rails generate [generator_type]

                         • more, and get help
                            > rails help [command]


Saturday, April 13, 13
Task 1: New Project



Saturday, April 13, 13
$ rails new mylibrary
                                     --skip-test-unit

                         $ cd mylibrary/

                         $ rails server

                         $ rm public/index.html




Saturday, April 13, 13
Project Directory(1)




Saturday, April 13, 13
Project Directory(2)




Saturday, April 13, 13
Task 2: Install Some
                         Gems & Import Specs


Saturday, April 13, 13
Gemfile: add haml-rails gem

                         $ bundle install

                         Gemfile: add rspec-rails

                         Gemfile: add capybara

                         $ bundle install

                         $ rails generate rspec:install

                         spec/spec_helper.rb:
                           require 'capybara-rails'



Saturday, April 13, 13
Task 3: Create Book
                                Model


Saturday, April 13, 13
$ rails generate model Book
                                            author:string
                                            title:string
                                            description:text
                                            publish_date:date

                         $ rake db:migrate



                         $ rails console

                         > Book.column_names



Saturday, April 13, 13
Task 4: Pass the
                         "Create" Book Spec


Saturday, April 13, 13
Task 5: Pass the
                         "Retrieve" Book Spec


Saturday, April 13, 13
Task 6: Pass the
                         "Update" Book Spec


Saturday, April 13, 13
Task 7: Pass the
                         "Destroy" Book Spec


Saturday, April 13, 13
Task 8: Refactor Routes



Saturday, April 13, 13
Task 9: Refactor Views



Saturday, April 13, 13
Task 10: Scaffold the
                              Category


Saturday, April 13, 13
$ rails generate model Category
                                            name:string

                         $ rake db:migrate



                         $ rails console

                         > Category.column_names




Saturday, April 13, 13
Task 11: Apply Models'
                          Associations


Saturday, April 13, 13
class Category < ActiveRecord::Base

                           has_many :books

                         end



                         class Book < ActiveRecord::Base

                           belongs_to :category

                         end




Saturday, April 13, 13
$ rails generate migration
                             add_category_id_to_books
                             category_id:integer:index

                         $ rake db:migrate




Saturday, April 13, 13
Task 12: Validate Inputs



Saturday, April 13, 13
class Book < ActiveRecord::Base

                           belongs_to :category

                           validates_presence_of :category_id,

                                                  :author,

                                                  :title

                         end




Saturday, April 13, 13
Task 13: Decorate
                         with Twitter Bootstrap


Saturday, April 13, 13
Task 14: Deploy to
                               Heroku


Saturday, April 13, 13
Assignments



Saturday, April 13, 13
Assignment 1:
                     Add a search bar above the book list
                  table on the index page, so the user can
                  search for books by author name or by
                  book title.




Saturday, April 13, 13
Assignment 2:
                      Add pagination links below the book
                  list table on the index page, so the user
                  can browse through 20 books per page.




Saturday, April 13, 13

More Related Content

Similar to Rails Intro & Tutorial

Intro to JavaScript Testing
Intro to JavaScript TestingIntro to JavaScript Testing
Intro to JavaScript TestingRan Mizrahi
 
Clojure basics
Clojure basicsClojure basics
Clojure basicsKyle Oba
 
Cook Up a Runtime with The New OSGi Resolver - Neil Bartlett
Cook Up a Runtime with The New OSGi Resolver - Neil BartlettCook Up a Runtime with The New OSGi Resolver - Neil Bartlett
Cook Up a Runtime with The New OSGi Resolver - Neil Bartlettmfrancis
 
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
 
Standing on the shoulders of giants with JRuby
Standing on the shoulders of giants with JRubyStanding on the shoulders of giants with JRuby
Standing on the shoulders of giants with JRubyTheo Hultberg
 
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
 
Improving Your Heroku App Performance with Asset CDN and Unicorn
Improving Your Heroku App Performance with Asset CDN and UnicornImproving Your Heroku App Performance with Asset CDN and Unicorn
Improving Your Heroku App Performance with Asset CDN and UnicornSimon Bagreev
 
Planning for the Horizontal: Scaling Node.js Applications
Planning for the Horizontal: Scaling Node.js ApplicationsPlanning for the Horizontal: Scaling Node.js Applications
Planning for the Horizontal: Scaling Node.js ApplicationsModulus
 
Riak intro to..
Riak intro to..Riak intro to..
Riak intro to..Adron Hall
 
Introduction to node.js by Ran Mizrahi @ Reversim Summit
Introduction to node.js by Ran Mizrahi @ Reversim SummitIntroduction to node.js by Ran Mizrahi @ Reversim Summit
Introduction to node.js by Ran Mizrahi @ Reversim SummitRan Mizrahi
 
Puppet and AWS: Getting the best of both worlds
Puppet and AWS: Getting the best of both worldsPuppet and AWS: Getting the best of both worlds
Puppet and AWS: Getting the best of both worldsPuppet
 
From a monolithic Ruby on Rails app to the JVM
From a monolithic  Ruby on Rails app  to the JVMFrom a monolithic  Ruby on Rails app  to the JVM
From a monolithic Ruby on Rails app to the JVMPhil Calçado
 
Mongo db php_shaken_not_stirred_joomlafrappe
Mongo db php_shaken_not_stirred_joomlafrappeMongo db php_shaken_not_stirred_joomlafrappe
Mongo db php_shaken_not_stirred_joomlafrappeSpyros Passas
 
Unleashing the Rails Asset Pipeline
Unleashing the Rails Asset PipelineUnleashing the Rails Asset Pipeline
Unleashing the Rails Asset PipelineKenneth Kalmer
 
Applying Evolutionary Architecture on a Popular API
Applying Evolutionary Architecture on a  Popular APIApplying Evolutionary Architecture on a  Popular API
Applying Evolutionary Architecture on a Popular APIPhil Calçado
 
Ab(Using) the MetaCPAN API for Fun and Profit v2013
Ab(Using) the MetaCPAN API for Fun and Profit v2013Ab(Using) the MetaCPAN API for Fun and Profit v2013
Ab(Using) the MetaCPAN API for Fun and Profit v2013Olaf Alders
 
Invokedynamic: Tales from the Trenches
Invokedynamic: Tales from the TrenchesInvokedynamic: Tales from the Trenches
Invokedynamic: Tales from the TrenchesCharles Nutter
 

Similar to Rails Intro & Tutorial (20)

Intro to JavaScript Testing
Intro to JavaScript TestingIntro to JavaScript Testing
Intro to JavaScript Testing
 
Clojure basics
Clojure basicsClojure basics
Clojure basics
 
Cook Up a Runtime with The New OSGi Resolver - Neil Bartlett
Cook Up a Runtime with The New OSGi Resolver - Neil BartlettCook Up a Runtime with The New OSGi Resolver - Neil Bartlett
Cook Up a Runtime with The New OSGi Resolver - Neil Bartlett
 
Intro tobackbone
Intro tobackboneIntro tobackbone
Intro tobackbone
 
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
 
How we're building Wercker
How we're building WerckerHow we're building Wercker
How we're building Wercker
 
Standing on the shoulders of giants with JRuby
Standing on the shoulders of giants with JRubyStanding on the shoulders of giants with JRuby
Standing on the shoulders of giants with JRuby
 
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
 
Improving Your Heroku App Performance with Asset CDN and Unicorn
Improving Your Heroku App Performance with Asset CDN and UnicornImproving Your Heroku App Performance with Asset CDN and Unicorn
Improving Your Heroku App Performance with Asset CDN and Unicorn
 
Planning for the Horizontal: Scaling Node.js Applications
Planning for the Horizontal: Scaling Node.js ApplicationsPlanning for the Horizontal: Scaling Node.js Applications
Planning for the Horizontal: Scaling Node.js Applications
 
Riak intro to..
Riak intro to..Riak intro to..
Riak intro to..
 
Introduction to node.js by Ran Mizrahi @ Reversim Summit
Introduction to node.js by Ran Mizrahi @ Reversim SummitIntroduction to node.js by Ran Mizrahi @ Reversim Summit
Introduction to node.js by Ran Mizrahi @ Reversim Summit
 
Puppet and AWS: Getting the best of both worlds
Puppet and AWS: Getting the best of both worldsPuppet and AWS: Getting the best of both worlds
Puppet and AWS: Getting the best of both worlds
 
From a monolithic Ruby on Rails app to the JVM
From a monolithic  Ruby on Rails app  to the JVMFrom a monolithic  Ruby on Rails app  to the JVM
From a monolithic Ruby on Rails app to the JVM
 
Mongo db php_shaken_not_stirred_joomlafrappe
Mongo db php_shaken_not_stirred_joomlafrappeMongo db php_shaken_not_stirred_joomlafrappe
Mongo db php_shaken_not_stirred_joomlafrappe
 
Unleashing the Rails Asset Pipeline
Unleashing the Rails Asset PipelineUnleashing the Rails Asset Pipeline
Unleashing the Rails Asset Pipeline
 
ElasticSearch
ElasticSearchElasticSearch
ElasticSearch
 
Applying Evolutionary Architecture on a Popular API
Applying Evolutionary Architecture on a  Popular APIApplying Evolutionary Architecture on a  Popular API
Applying Evolutionary Architecture on a Popular API
 
Ab(Using) the MetaCPAN API for Fun and Profit v2013
Ab(Using) the MetaCPAN API for Fun and Profit v2013Ab(Using) the MetaCPAN API for Fun and Profit v2013
Ab(Using) the MetaCPAN API for Fun and Profit v2013
 
Invokedynamic: Tales from the Trenches
Invokedynamic: Tales from the TrenchesInvokedynamic: Tales from the Trenches
Invokedynamic: Tales from the Trenches
 

Recently uploaded

Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 

Recently uploaded (20)

Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 

Rails Intro & Tutorial

  • 1. Ruby On Rails Intro & Tutorial Mason Chang Saturday, April 13, 13
  • 2. Who I am? • Mason Chang (張銘軒) • Works at OptimisDev • twitter: @changmason • github: https://github.com/changmason Saturday, April 13, 13
  • 5. Rails is... http://rubyonrails.org/ Saturday, April 13, 13
  • 6. Rails is... • Created by DHH of 37signals in 2004 • Extracted from product Basecamp • Of course, written in Ruby Saturday, April 13, 13
  • 8. Don't Repeat Yourself • Code generators • Rake tasks • Extentions Saturday, April 13, 13
  • 9. Code generators • Generate new project • Generate models • Generate controllers & views Saturday, April 13, 13
  • 10. Rake tasks • Run tests • Manipulate database • Show useful info Saturday, April 13, 13
  • 11. Extensions • Sensible core extensions • Helper methods • A lot of 3rd party gems Saturday, April 13, 13
  • 12. Convention over Configuration(1) • Convention for environments development, test and production • Convention for organizing code • Convention for organizing assets Saturday, April 13, 13
  • 13. Convention over Configuration(2) • Convention for models model names - table names model attributes - record fields • Convention for controllers & views controller actions - view templates Saturday, April 13, 13
  • 17. Combine HTTP verb and path to dispatch requests to corresponding handlers (actions) http://guides.rubyonrails.org/routing.html Saturday, April 13, 13
  • 18. A very simple blog in 5 minute Saturday, April 13, 13
  • 21. What is ActiveRecord? • ORM, Object-Relational Mapping • Dealing with SQL • A standalone Module • Tons of functionalities Saturday, April 13, 13
  • 22. $ gem install activerecord $ irb > require 'rubygems' > require 'active_record' > ActiveRecord::VERSION::STRING Saturday, April 13, 13
  • 23. ActiveRecord can connect to existing DB > ActiveRecord::Base.establish_connection( :adapter => 'mysql2', :database => 'fju_test_db', :username => 'root', :password => '******' ) > ActiveRecord::Base.connection > ActiveRecord::Base.connected? Saturday, April 13, 13
  • 24. ActiveRecord can migrate existing DB > ARConnection = AR::Base.connection > ARConnection.create_table(:users) do |t| t.string :name t.integer :age t.timestamps end > ARConnection.add_index(:users, 'name') Saturday, April 13, 13
  • 25. ActiveRecord can execute raw SQL > ARConnection = AR::Base.connection > ARConnection.execute(%q{ INSERT INTO users (name, age) VALUES ('Mason Chang', 30) }) > resultes = ARConnection.execute(%q{ SELECT * FROM users WHERE age = 30 }) > results.fields > results.first Saturday, April 13, 13
  • 26. User Model > class User < ActiveRecord::Base end > require 'logger' > ActiveRecord::Base.logger = Logger.new(STDOUT) Saturday, April 13, 13
  • 27. Model can create records > user.newser = User.new( :name => 'Eddie Kao', :age => 20) > user.save > User.create( :name => 'Ryudo Teng', :age => 20) Saturday, April 13, 13
  • 28. Model can retrieve records > User.first > User.last > User.all > User.find(1) > User.find([1,2,3]) > User.find(:first, :conditions => {:name => 'Eddie Kao'}) > User.find(:all, :conditions => ['age < ?', 30]) Saturday, April 13, 13
  • 29. Model can update records > user = User.find_by_name('Mason Chang') > user.age = 10 > user.save > user.update_attribute(:age, 20) > user.update_attributes( :name => 'Ming-hsuan Chang' :age => 30) > User.update(1, :age => 40) > User.update_all( {:age => 50}, ['age >= ?', 20]) Saturday, April 13, 13
  • 30. Model can delete records > user = User.first > user.delete # callbacks ignored > user.destroy # callbacks triggered > User.delete(1) # callbacks ignored > User.destroy(1) # callbacks triggered Saturday, April 13, 13
  • 31. Model can do validations > class User validates_presence_of :name validates_numericality_of :age end > user = User.new(:age => 'thirty") > user.save # fail > user.errors.messages http://guides.rubyonrails.org/active_record_validations_callbacks.html Saturday, April 13, 13
  • 32. Model can have callbacks • Callbacks are operations which hooked into the lifecycle of an ActiveRecord object • Object's lifecycle includes: creating, updating and destroying an object after initializing and finding an object http://guides.rubyonrails.org/active_record_validations_callbacks.html Saturday, April 13, 13
  • 33. Callbacks for creating an object • before_validation • after_validation • before_save • around_save • before_create • around_create • after_create • after_save Saturday, April 13, 13
  • 34. Callbacks for updating an object • before_validation • after_validation • before_save • around_save • before_update • around_update • after_update • after_save Saturday, April 13, 13
  • 35. Callbacks for destroying an object • before_destroy • around_destroy • after_destroy Saturday, April 13, 13
  • 36. Model can have associations • One-to-one • One-to-many • Many-to-many • and more... http://guides.rubyonrails.org/association_basics.html Saturday, April 13, 13
  • 38. One-to-many association Saturday, April 13, 13
  • 39. Many-to-many association Saturday, April 13, 13
  • 41. Task 0: Install Rails Saturday, April 13, 13
  • 42. $ gem install rails $ rails --version Saturday, April 13, 13
  • 43. The rails command • create new project > rails new [project_name] • start server > rails server • start console > rails console • execute generator > rails generate [generator_type] • more, and get help > rails help [command] Saturday, April 13, 13
  • 44. Task 1: New Project Saturday, April 13, 13
  • 45. $ rails new mylibrary --skip-test-unit $ cd mylibrary/ $ rails server $ rm public/index.html Saturday, April 13, 13
  • 48. Task 2: Install Some Gems & Import Specs Saturday, April 13, 13
  • 49. Gemfile: add haml-rails gem $ bundle install Gemfile: add rspec-rails Gemfile: add capybara $ bundle install $ rails generate rspec:install spec/spec_helper.rb: require 'capybara-rails' Saturday, April 13, 13
  • 50. Task 3: Create Book Model Saturday, April 13, 13
  • 51. $ rails generate model Book author:string title:string description:text publish_date:date $ rake db:migrate $ rails console > Book.column_names Saturday, April 13, 13
  • 52. Task 4: Pass the "Create" Book Spec Saturday, April 13, 13
  • 53. Task 5: Pass the "Retrieve" Book Spec Saturday, April 13, 13
  • 54. Task 6: Pass the "Update" Book Spec Saturday, April 13, 13
  • 55. Task 7: Pass the "Destroy" Book Spec Saturday, April 13, 13
  • 56. Task 8: Refactor Routes Saturday, April 13, 13
  • 57. Task 9: Refactor Views Saturday, April 13, 13
  • 58. Task 10: Scaffold the Category Saturday, April 13, 13
  • 59. $ rails generate model Category name:string $ rake db:migrate $ rails console > Category.column_names Saturday, April 13, 13
  • 60. Task 11: Apply Models' Associations Saturday, April 13, 13
  • 61. class Category < ActiveRecord::Base has_many :books end class Book < ActiveRecord::Base belongs_to :category end Saturday, April 13, 13
  • 62. $ rails generate migration add_category_id_to_books category_id:integer:index $ rake db:migrate Saturday, April 13, 13
  • 63. Task 12: Validate Inputs Saturday, April 13, 13
  • 64. class Book < ActiveRecord::Base belongs_to :category validates_presence_of :category_id, :author, :title end Saturday, April 13, 13
  • 65. Task 13: Decorate with Twitter Bootstrap Saturday, April 13, 13
  • 66. Task 14: Deploy to Heroku Saturday, April 13, 13
  • 68. Assignment 1: Add a search bar above the book list table on the index page, so the user can search for books by author name or by book title. Saturday, April 13, 13
  • 69. Assignment 2: Add pagination links below the book list table on the index page, so the user can browse through 20 books per page. Saturday, April 13, 13