Introduction to Rails

52
Introduction to Ruby on Rails Presented by: Arman Ortega rubyonrails.org

Transcript of Introduction to Rails

Page 1: Introduction to Rails

Introduction to Ruby on Rails

Presented by: Arman Ortega

rubyonrails.org

Page 2: Introduction to Rails

What you'll learn➔ Overview of Ruby➔ Overview of Rails➔ Convention over Configuration➔ CRUD – Create, Read, Update & Delete➔ Sample Rails app (Blog)➔ Short Activity (railszombies.org)

Page 3: Introduction to Rails

Ruby is object oriented

Everything is an object. Integers, Floats, Booleans, Strings, Arrays, Hash – all are objects. Ruby is simple, elegant & natural syntax Inspired by Perl, Python, LISP Less lines of code, higher productivity

In PHP:function say_hi($name) { $out = "Hi $name "; return $out;}

say_hi("Michelle");

In Ruby:def say_hi name out = "Hi #{name} " outend

say_hi "Michelle"

Page 4: Introduction to Rails

Interactive Ruby (irb)

irb(main):001:0> s = "Hello World" => "Hello World"irb(main):002:0> s.length => 11irb(main):003:0> s.upcase => "HELLO WORLD" irb(main):004:0> s.downcase => "hello world" irb(main):005:0> s.downcase.reverse => "dlrow olleh"

irb(main):006:0> n = 2 + 3 => 5irb(main):007:0> n.class => Fixnumirb(main):008:0> 5.times { print s }Hello WorldHello WorldHello WorldHello WorldHello World

C:\Ruby193\bin>irb

Provides a shell(command prompt) for experimentation.

String method

String class

Fixnum class

Page 5: Introduction to Rails

Arrays - are ordered, integer-indexed collections of any object. Indexing starts at 0, as in C or Java.

e.g. pet = Array.new or []irb> pet = ["dog", "cat", "mouse"]

irb> pet.count

=> 3

irb> pet.index("cat") => 1

irb> pet[2]

=> "mouse"

Hashes - is a collection of key-value pairs.e.g. style = Hash.new or {}

irb> style = { "font_size" => 10, "font_family" => "Arial" }

=> {"font_size"=>10, "font_family"=>"Arial"}

irb> style["font_size"]

=> 10

Arrays & Hashes

Page 6: Introduction to Rails

More about Ruby

http://tryruby.org – an interactive tutorial

https://www.ruby-lang.org/en/documentation

Page 7: Introduction to Rails

What is Rails? Rails is an open-source web framework that’s optimized for programmer

happiness and sustainable productivity. Less lines of code, higher productivity. It is an MVC web framework where Models, Views and Controllers are fully

integrated. Written in Ruby language.

http://rubyonrails.org/ https://www.ruby-lang.org/en/

Page 8: Introduction to Rails

Overview of Rails

Convention over Configuration ActiveRecord

– is the M in MVC – the model.

– It is the Object/Relational Mapping (ORM) layer supplied with Rails. It closely follows the standard ORM model such as:* tables map to classes* columns map to object attributes* rows map to objects

id title body1 hello world

Table: articles

a = Article.new

Object attribute

a.title

Page 9: Introduction to Rails

Convention over ConfigurationDatabase Table - Plural with underscores separating words (e.g. articles, asset_images )Model Class - Singular with the first letter of each word capitalized (e.g. Article, AssetImage)Filenames are written in lowercase, with underscores separating each word.

id int(11)title varchar(255)body textcreated_at datetimeupdated_at datetime

Table: articles

class Article < ActiveRecord::Base. . .end

File: models/article.rb

Class name FilenameUserController user_controller.rbStatusMessagesController status_messages_controller.rbRemoteUploader remote_uploader.rb

Another example:

Example:

Page 10: Introduction to Rails

CRUD: Create, Read, Update & DeleteCreate

example:a = Article.newa.title = "hello"a.body = "world"a.save

ReadModelClass.find(id)

example:Article.find(1)

ModelClass.where()example:Article.where("title = ?", "MH17")

m = ModelClass.newm.attribute = valuem.save

syntax:

More details: http://guides.rubyonrails.org/active_record_basics.html

Page 11: Introduction to Rails

CRUD: Create, Read, Update & DeleteUpdatem = ModelClass.find_by(field: value)m.attribute = valuem.save

example:a = Article.find_by(id: 1)a.title = "hello"a.body = "world"a.save

Deletea = ModelClass.find_by(field: value)a.destroy

example:a = Article.find_by(title:"hi")a.destroy

m = ModelClass.find_by(field1:value, field2: value)m.update(field1: value1, field2: value2)

m = Article.find_by(title: "lorem1", body: "lorem1")m.update(title: "lorem2", body: "lorem2")

Alternative way

Page 12: Introduction to Rails

Installing RailsFor Windows

Rails Installer 2.2.3 (http://railsinstaller.org/en)Packages included are:RubyRailsBundler -manage your gem dependenciesGit. . .

XAMPP 1.8.2 (https://www.apachefriends.org/download.html)Packages included are:Apache 2MySQL 5.6PHP 5phpMyAdmin. . .

For Linux, see the links below on how to install Rails on Linuxhttp://coding.smashingmagazine.com/2011/06/21/set-up-an-ubuntu-local-development-machine-for-ruby-on-rails/http://www.computersnyou.com/1535/2013/03/installing-ruby-on-rail-on-ubuntu-with-rbenv-step-by-step/https://help.ubuntu.com/community/RubyOnRails

Page 13: Introduction to Rails

Step 1 of 3 Step 2 of 3

Step 3 of 3How to verify the load path in Ruby?> ruby -e 'puts $:'C:/RailsInstaller/Ruby1.9.3/lib/ruby/site_ruby/1.9.1C:/RailsInstaller/Ruby1.9.3/lib/ruby/site_ruby/1.9.1/i386-msvcrtC:/RailsInstaller/Ruby1.9.3/lib/ruby/site_rubyC:/RailsInstaller/Ruby1.9.3/lib/ruby/vendor_ruby/1.9.1C:/RailsInstaller/Ruby1.9.3/lib/ruby/1.9.1C:/RailsInstaller/Ruby1.9.3/lib/ruby/1.9.1/i386-mingw32

Installing Rails Installer on Windows

Page 14: Introduction to Rails

Installing XAMPP on Windows

Page 15: Introduction to Rails

Some common errors during setup

Problem: Error installing mysql2: ERROR: Failed to build gem native extension.

Solution:> gem install mysql2 -- '--with-mysql-lib="C:\xampp\mysql\lib" --with-mysql-include="C:\xampp\mysql\include"'

Problem: Incorrect MySQL client library version! This gem was compiled for 5.6.16 but the client library is 5.5.27. (RuntimeError)

Solution:You need to copy libmysql.dll from MySQL installation directory(e.g. c:\>xampp\mysql\lib) and paste it to C:\RailsInstaller2.2.3\Ruby1.9.3\bin

Page 16: Introduction to Rails

Sample Rails app (blog)

> rails new APP_NAME --database=mysqle.g. rails new blog --database=mysql

createcreate README.rdoccreate Rakefilecreate config.rucreate .gitignorecreate Gemfilecreate appcreate app/assets/javascripts/application.jscreate app/assets/stylesheets/application.csscreate app/controllers/application_controller.rbcreate app/helpers/application_helper.rbcreate app/views/layouts/application.html.erb. . .run bundle installFetching gem metadata from https://rubygems.org/...........Fetching additional metadata from https://rubygems.org/..Resolving dependencies...Using rake 10.3.2Using i18n 0.6.11Using activerecord 4.1.4Using bundler 1.6.2. . .Your bundle is complete!

Page 17: Introduction to Rails

Rails directory structure+-app| +-assets| | +-images| | +-javascripts| | +-stylesheets| +-controllers| +-helpers| +-mailers| +-models| +-views+-config (database.yml, routes.rb, application.rb, etc)+-db (migration files)+-lib+-log (log files used for debugging)+-public (404.html, favicon.ico, robots.txt)+-test+-vendor (third-party javascripts/css like twitter-bootstrap or jquery ) +-images +-javascripts +-stylesheetsGemfileREADME.rdoc

Page 18: Introduction to Rails

config/database.yml

development: adapter: mysql2 database: blog_dev username: root password: host: localhost

test: adapter: mysql2 database: blog_test username: root password: host: localhost

production: adapter: mysql2 database: blog_prod username: root password: host: localhost

After configuring the database.yml. Then, let's create all databases

> rake db:create:allRake is used for common administration tasks.Sample rake commands are:> rake db:migrate RAILS_ENV=development> rake db:create:all> rake routes

To run the appC:\railsapp\APP_NAME> rails s

Page 19: Introduction to Rails

config/routes.rb

Rails.application.routes.draw doget 'articles/add', to: 'articles#add', as: 'articles_add' get 'articles/:id', to: 'articles#details', as: 'articles_details' get 'articles/:id/edit', to: 'articles#edit', as: 'articles_edit' get 'articles/:id/delete', to: 'articles#delete', as: 'articles_delete'

post 'articles/save', to: 'articles#save', as: 'articles_save' post 'articles/update', to: 'articles#update', as: 'articles_update'

get 'welcome/index', to: 'welcome#index', as: 'welcome_index' root 'welcome#index'

end

Page 20: Introduction to Rails

Router

In controller:def details@article = Article.find params[:id]end

The Rails router recognizes URLs and dispatches them to a controller's action.

GET articles/1In routes.rb

get '/articles/:id', to: 'articles#details', as: 'articles_details'

get 'welcome/index', to: 'welcome#index', as: 'welcome_index' . . .

In views:<div class="article"> <em><%= time_ago_in_words(@article.updated_at) %> ago</em> <h3><%= @article.title %></h3> <p><%= @article.body %></p> <%= link_to "<<Back to Home", welcome_index_path %> </div>

Page 21: Introduction to Rails

Running the app

'rails server' or 'rails s' command> rails s=> Booting WEBrick=> Rails 4.1.4 application starting in development

on http://0.0.0.0:3000=> Run `rails server -h` for more startup options=> Notice: server is listening on all interfaces

(0.0.0.0). Consider using 127.0.0.1 (--binding option)

=> Ctrl-C to shutdown server

Page 22: Introduction to Rails

Creating a Controller

'rails generate' or 'rails g' commandrails generate controller <NAME> <action1> <action2> . . . e.g. > rails generate controller Welcome index

create app/controllers/welcome_controller.rb route get 'welcome/index‘invoke erbcreate app/views/welcomecreate app/views/welcome/index.html.erb. . .

> rails generate controller Articles add save edit updatecreate app/controllers/articles_controller.rb route get 'articles/update' route get 'articles/edit' route get 'articles/add'invoke erbcreate app/views/articlescreate app/views/articles/add.html.erbcreate app/views/articles/edit.html.erbcreate app/views/articles/delete.html.erb. . .

More info: http://guides.rubyonrails.org/command_line.html#rails-generate

Page 23: Introduction to Rails

Creating a Modelrails generate model <MODEL_NAME> <field1:type> <field2:type> . . .e.g.

> rails generate model Article title:string body:text invoke active_recordcreate db/migrate/20140705184622_create_articles.rbcreate app/models/article.rb. . .. . .

File: db/migrate/20140705184622_create_articles.rb

File: app/models/article.rb

Page 24: Introduction to Rails

Creating a viewsFile: views/articles/add.html.erb

More info: http://guides.rubyonrails.org/form_helpers.html

Page 25: Introduction to Rails

Useful links

https://www.ruby-lang.org/en/documentation/ http://guides.rubyonrails.org/getting_started.html http://tryruby.org http://railsforzombies.org

Page 26: Introduction to Rails

Thank you!

Page 27: Introduction to Rails

8/8/14 1

Introduction to Ruby on Rails

Presented by: Arman Ortega

rubyonrails.org

Page 28: Introduction to Rails

8/8/14 2

What you'll learn➔ Overview of Ruby➔ Overview of Rails➔ Convention over Configuration➔ CRUD – Create, Read, Update & Delete➔ Sample Rails app (Blog)➔ Short Activity (railszombies.org)

Page 29: Introduction to Rails

8/8/14 3

Ruby is object oriented

Everything is an object. Integers, Floats, Booleans, Strings, Arrays, Hash – all are objects. Ruby is simple, elegant & natural syntax Inspired by Perl, Python, LISP Less lines of code, higher productivity

In PHP:function say_hi($name) { $out = "Hi $name "; return $out;}

say_hi("Michelle");

In Ruby:def say_hi name out = "Hi #{name} " outend

say_hi "Michelle"

Page 30: Introduction to Rails

8/8/14 4

Interactive Ruby (irb)

irb(main):001:0> s = "Hello World" => "Hello World"irb(main):002:0> s.length => 11irb(main):003:0> s.upcase => "HELLO WORLD" irb(main):004:0> s.downcase => "hello world" irb(main):005:0> s.downcase.reverse => "dlrow olleh"

irb(main):006:0> n = 2 + 3 => 5irb(main):007:0> n.class => Fixnumirb(main):008:0> 5.times { print s }Hello WorldHello WorldHello WorldHello WorldHello World

C:\Ruby193\bin>irb

Provides a shell(command prompt) for experimentation.

String method

String class

Fixnum class

Page 31: Introduction to Rails

8/8/14 5

Arrays - are ordered, integer-indexed collections of any object. Indexing starts at 0, as in C or Java.

e.g. pet = Array.new or []irb> pet = ["dog", "cat", "mouse"]

irb> pet.count => 3

irb> pet.index("cat") => 1

irb> pet[2] => "mouse"

Hashes - is a collection of key-value pairs.e.g. style = Hash.new or {}

irb> style = { "font_size" => 10, "font_family" => "Arial" }

=> {"font_size"=>10, "font_family"=>"Arial"}

irb> style["font_size"]

=> 10

Arrays & Hashes

Page 32: Introduction to Rails

8/8/14 6

More about Ruby

http://tryruby.org – an interactive tutorial

https://www.ruby-lang.org/en/documentation

Page 33: Introduction to Rails

8/8/14 7

What is Rails? Rails is an open-source web framework that’s optimized for programmer

happiness and sustainable productivity. Less lines of code, higher productivity. It is an MVC web framework where Models, Views and Controllers are fully

integrated. Written in Ruby language.

http://rubyonrails.org/ https://www.ruby-lang.org/en/

Page 34: Introduction to Rails

8/8/14 8

Overview of Rails

Convention over Configuration ActiveRecord

– is the M in MVC – the model.

– It is the Object/Relational Mapping (ORM) layer supplied with Rails. It closely follows the standard ORM model such as:* tables map to classes* columns map to object attributes* rows map to objects

id title body1 hello world

Table: articles

a = Article.new

Object attribute

a.title

Page 35: Introduction to Rails

8/8/14 9

Convention over ConfigurationDatabase Table - Plural with underscores separating words (e.g. articles, asset_images )Model Class - Singular with the first letter of each word capitalized (e.g. Article, AssetImage)Filenames are written in lowercase, with underscores separating each word.

id int(11)title varchar(255)body textcreated_at datetimeupdated_at datetime

Table: articles

class Article < ActiveRecord::Base. . .end

File: models/article.rb

Class name FilenameUserController user_controller.rbStatusMessagesController status_messages_controller.rbRemoteUploader remote_uploader.rb

Another example:

Example:

Page 36: Introduction to Rails

8/8/14 10

CRUD: Create, Read, Update & DeleteCreate

example:a = Article.newa.title = "hello"a.body = "world"a.save

ReadModelClass.find(id)

example:Article.find(1)

ModelClass.where()example:Article.where("title = ?", "MH17")

m = ModelClass.newm.attribute = valuem.save

syntax:

More details: http://guides.rubyonrails.org/active_record_basics.html

Page 37: Introduction to Rails

8/8/14 11

CRUD: Create, Read, Update & DeleteUpdatem = ModelClass.find_by(field: value)m.attribute = valuem.save

example:a = Article.find_by(id: 1)a.title = "hello"a.body = "world"a.save

Deletea = ModelClass.find_by(field: value)a.destroy

example:a = Article.find_by(title:"hi")a.destroy

m = ModelClass.find_by(field1:value, field2: value)m.update(field1: value1, field2: value2)

m = Article.find_by(title: "lorem1", body: "lorem1")m.update(title: "lorem2", body: "lorem2")

Alternative way

Page 38: Introduction to Rails

8/8/14 12

Installing RailsFor Windows

Rails Installer 2.2.3 (http://railsinstaller.org/en)Packages included are:RubyRailsBundler -manage your gem dependenciesGit. . .

XAMPP 1.8.2 (https://www.apachefriends.org/download.html)Packages included are:Apache 2MySQL 5.6PHP 5phpMyAdmin. . .

For Linux, see the links below on how to install Rails on Linuxhttp://coding.smashingmagazine.com/2011/06/21/set-up-an-ubuntu-local-development-machine-for-ruby-on-rails/http://www.computersnyou.com/1535/2013/03/installing-ruby-on-rail-on-ubuntu-with-rbenv-step-by-step/https://help.ubuntu.com/community/RubyOnRails

Page 39: Introduction to Rails

8/8/14 13

Step 1 of 3 Step 2 of 3

Step 3 of 3How to verify the load path in Ruby?> ruby -e 'puts $:'C:/RailsInstaller/Ruby1.9.3/lib/ruby/site_ruby/1.9.1C:/RailsInstaller/Ruby1.9.3/lib/ruby/site_ruby/1.9.1/i386-msvcrtC:/RailsInstaller/Ruby1.9.3/lib/ruby/site_rubyC:/RailsInstaller/Ruby1.9.3/lib/ruby/vendor_ruby/1.9.1C:/RailsInstaller/Ruby1.9.3/lib/ruby/1.9.1C:/RailsInstaller/Ruby1.9.3/lib/ruby/1.9.1/i386-mingw32

Installing Rails Installer on Windows

Page 40: Introduction to Rails

8/8/14 14

Installing XAMPP on Windows

Page 41: Introduction to Rails

8/8/14 15

Some common errors during setup

Problem: Error installing mysql2: ERROR: Failed to build gem native extension.

Solution:> gem install mysql2 -- '--with-mysql-lib="C:\xampp\mysql\lib" --with-mysql-include="C:\xampp\mysql\include"'

Problem: Incorrect MySQL client library version! This gem was compiled for 5.6.16 but the client library is 5.5.27. (RuntimeError)

Solution:You need to copy libmysql.dll from MySQL installation directory(e.g. c:\>xampp\mysql\lib) and paste it to C:\RailsInstaller2.2.3\Ruby1.9.3\bin

Page 42: Introduction to Rails

8/8/14 16

Sample Rails app (blog)

> rails new APP_NAME --database=mysqle.g. rails new blog --database=mysql

createcreate README.rdoccreate Rakefilecreate config.rucreate .gitignorecreate Gemfilecreate appcreate app/assets/javascripts/application.jscreate app/assets/stylesheets/application.csscreate app/controllers/application_controller.rbcreate app/helpers/application_helper.rbcreate app/views/layouts/application.html.erb. . .run bundle installFetching gem metadata from https://rubygems.org/...........Fetching additional metadata from https://rubygems.org/..Resolving dependencies...Using rake 10.3.2Using i18n 0.6.11Using activerecord 4.1.4Using bundler 1.6.2. . .Your bundle is complete!

Page 43: Introduction to Rails

8/8/14 17

Rails directory structure+-app| +-assets| | +-images| | +-javascripts| | +-stylesheets| +-controllers| +-helpers| +-mailers| +-models| +-views+-config (database.yml, routes.rb, application.rb, etc)+-db (migration files)+-lib+-log (log files used for debugging)+-public (404.html, favicon.ico, robots.txt)+-test+-vendor (third-party javascripts/css like twitter-bootstrap or jquery ) +-images +-javascripts +-stylesheetsGemfileREADME.rdoc

Page 44: Introduction to Rails

8/8/14 18

config/database.yml

development: adapter: mysql2 database: blog_dev username: root password: host: localhost

test: adapter: mysql2 database: blog_test username: root password: host: localhost

production: adapter: mysql2 database: blog_prod username: root password: host: localhost

After configuring the database.yml. Then, let's create all databases

> rake db:create:allRake is used for common administration tasks.Sample rake commands are:> rake db:migrate RAILS_ENV=development> rake db:create:all> rake routes

To run the appC:\railsapp\APP_NAME> rails s

Page 45: Introduction to Rails

8/8/14 19

config/routes.rb

Rails.application.routes.draw doget 'articles/add', to: 'articles#add', as: 'articles_add' get 'articles/:id', to: 'articles#details', as: 'articles_details' get 'articles/:id/edit', to: 'articles#edit', as: 'articles_edit' get 'articles/:id/delete', to: 'articles#delete', as: 'articles_delete'

post 'articles/save', to: 'articles#save', as: 'articles_save' post 'articles/update', to: 'articles#update', as: 'articles_update'

get 'welcome/index', to: 'welcome#index', as: 'welcome_index' root 'welcome#index'

end

Page 46: Introduction to Rails

8/8/14 20

Router

In controller:def details@article = Article.find params[:id]end

The Rails router recognizes URLs and dispatches them to a controller's action.

GET articles/1In routes.rb

get '/articles/:id', to: 'articles#details', as: 'articles_details'

get 'welcome/index', to: 'welcome#index', as: 'welcome_index' . . .

In views:<div class="article"> <em><%= time_ago_in_words(@article.updated_at) %> ago</em> <h3><%= @article.title %></h3> <p><%= @article.body %></p> <%= link_to "<<Back to Home", welcome_index_path %> </div>

Page 47: Introduction to Rails

8/8/14 21

Running the app

'rails server' or 'rails s' command> rails s=> Booting WEBrick=> Rails 4.1.4 application starting in development

on http://0.0.0.0:3000=> Run `rails server -h` for more startup options=> Notice: server is listening on all interfaces

(0.0.0.0). Consider using 127.0.0.1 (--binding option)

=> Ctrl-C to shutdown server

Page 48: Introduction to Rails

8/8/14 22

Creating a Controller

'rails generate' or 'rails g' commandrails generate controller <NAME> <action1> <action2> . . . e.g. > rails generate controller Welcome index

create app/controllers/welcome_controller.rb route get 'welcome/index‘invoke erbcreate app/views/welcomecreate app/views/welcome/index.html.erb. . .

> rails generate controller Articles add save edit updatecreate app/controllers/articles_controller.rb route get 'articles/update' route get 'articles/edit' route get 'articles/add'invoke erbcreate app/views/articlescreate app/views/articles/add.html.erbcreate app/views/articles/edit.html.erbcreate app/views/articles/delete.html.erb. . .

More info: http://guides.rubyonrails.org/command_line.html#rails-generate

Page 49: Introduction to Rails

8/8/14 23

Creating a Modelrails generate model <MODEL_NAME> <field1:type> <field2:type> . . .e.g.

> rails generate model Article title:string body:text invoke active_recordcreate db/migrate/20140705184622_create_articles.rbcreate app/models/article.rb. . .. . .

File: db/migrate/20140705184622_create_articles.rb

File: app/models/article.rb

Page 50: Introduction to Rails

8/8/14 24

Creating a viewsFile: views/articles/add.html.erb

More info: http://guides.rubyonrails.org/form_helpers.html

Page 51: Introduction to Rails

8/8/14 25

Useful links

https://www.ruby-lang.org/en/documentation/ http://guides.rubyonrails.org/getting_started.html http://tryruby.org http://railsforzombies.org

Page 52: Introduction to Rails

8/8/14 26

Thank you!