69
Ruby On Rails Intro & Tutorial Mason Chang Saturday, April 13, 13

Rails Intro & Tutorial

Embed Size (px)

DESCRIPTION

A rails introduction and tutorial course for FJU

Citation preview

Page 1: Rails Intro & Tutorial

Ruby On Rails Intro & Tutorial

Mason Chang

Saturday, April 13, 13

Page 2: Rails Intro & Tutorial

Who I am?

• Mason Chang (張銘軒)

• Works at OptimisDev

• twitter: @changmason

• github: https://github.com/changmason

Saturday, April 13, 13

Page 3: Rails Intro & Tutorial

Part I

Saturday, April 13, 13

Page 4: Rails Intro & Tutorial

What is Rails?

Saturday, April 13, 13

Page 5: Rails Intro & Tutorial

Rails is...

http://rubyonrails.org/

Saturday, April 13, 13

Page 6: Rails Intro & Tutorial

Rails is...

• Created by DHH of 37signals in 2004

• Extracted from product Basecamp

• Of course, written in Ruby

Saturday, April 13, 13

Page 7: Rails Intro & Tutorial

Rails Philosophy

Saturday, April 13, 13

Page 8: Rails Intro & Tutorial

Don't Repeat Yourself

• Code generators

• Rake tasks

• Extentions

Saturday, April 13, 13

Page 9: Rails Intro & Tutorial

Code generators

• Generate new project

• Generate models

• Generate controllers & views

Saturday, April 13, 13

Page 10: Rails Intro & Tutorial

Rake tasks

• Run tests

• Manipulate database

• Show useful info

Saturday, April 13, 13

Page 11: Rails Intro & Tutorial

Extensions

• Sensible core extensions

• Helper methods

• A lot of 3rd party gems

Saturday, April 13, 13

Page 12: Rails Intro & Tutorial

Convention over Configuration(1)

• Convention for environments development, test and production

• Convention for organizing code

• Convention for organizing assets

Saturday, April 13, 13

Page 13: Rails Intro & Tutorial

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

Page 14: Rails Intro & Tutorial

MVC Architecture

Saturday, April 13, 13

Page 15: Rails Intro & Tutorial

http://betterexplained.com/articles/intermediate-rails-understanding-models-views-and-controllers/

Saturday, April 13, 13

Page 16: Rails Intro & Tutorial

RESTful Routes

Saturday, April 13, 13

Page 17: Rails Intro & Tutorial

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

Combine HTTP verb and path to dispatch requests to corresponding

handlers (actions)

Saturday, April 13, 13

Page 18: Rails Intro & Tutorial

A very simple blogin 5 minute

Saturday, April 13, 13

Page 19: Rails Intro & Tutorial

Part II

Saturday, April 13, 13

Page 20: Rails Intro & Tutorial

ActiveRecord & Model

Saturday, April 13, 13

Page 21: Rails Intro & Tutorial

What is ActiveRecord?

• ORM, Object-Relational Mapping

• Dealing with SQL

• A standalone Module

• Tons of functionalities

Saturday, April 13, 13

Page 22: Rails Intro & Tutorial

$ gem install activerecord $ irb

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

Saturday, April 13, 13

Page 23: Rails Intro & Tutorial

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

Page 24: Rails Intro & Tutorial

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

Page 25: Rails Intro & Tutorial

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

Page 26: Rails Intro & Tutorial

User Model

> class User < ActiveRecord::Base end

> require 'logger'

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

Saturday, April 13, 13

Page 27: Rails Intro & Tutorial

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

Page 28: Rails Intro & Tutorial

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

Page 29: Rails Intro & Tutorial

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

Page 30: Rails Intro & Tutorial

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

Page 31: Rails Intro & Tutorial

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

Page 32: Rails Intro & Tutorial

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

Page 33: Rails Intro & Tutorial

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

Page 34: Rails Intro & Tutorial

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

Page 35: Rails Intro & Tutorial

Callbacks for destroying an object

• before_destroy

• around_destroy

• after_destroy

Saturday, April 13, 13

Page 36: Rails Intro & Tutorial

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

Page 37: Rails Intro & Tutorial

One-to-one association

Saturday, April 13, 13

Page 38: Rails Intro & Tutorial

One-to-many association

Saturday, April 13, 13

Page 39: Rails Intro & Tutorial

Many-to-many association

Saturday, April 13, 13

Page 40: Rails Intro & Tutorial

Part III

Saturday, April 13, 13

Page 41: Rails Intro & Tutorial

Task 0: Install Rails

Saturday, April 13, 13

Page 42: Rails Intro & Tutorial

$ gem install rails

$ rails --version

Saturday, April 13, 13

Page 43: Rails Intro & Tutorial

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

Page 44: Rails Intro & Tutorial

Task 1: New Project

Saturday, April 13, 13

Page 45: Rails Intro & Tutorial

$ rails new mylibrary --skip-test-unit

$ cd mylibrary/

$ rails server

$ rm public/index.html

Saturday, April 13, 13

Page 46: Rails Intro & Tutorial

Project Directory(1)

Saturday, April 13, 13

Page 47: Rails Intro & Tutorial

Project Directory(2)

Saturday, April 13, 13

Page 48: Rails Intro & Tutorial

Task 2: Install Some Gems & Import Specs

Saturday, April 13, 13

Page 49: Rails Intro & Tutorial

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

Page 50: Rails Intro & Tutorial

Task 3: Create Book Model

Saturday, April 13, 13

Page 51: Rails Intro & Tutorial

$ 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

Page 52: Rails Intro & Tutorial

Task 4: Pass the "Create" Book Spec

Saturday, April 13, 13

Page 53: Rails Intro & Tutorial

Task 5: Pass the "Retrieve" Book Spec

Saturday, April 13, 13

Page 54: Rails Intro & Tutorial

Task 6: Pass the "Update" Book Spec

Saturday, April 13, 13

Page 55: Rails Intro & Tutorial

Task 7: Pass the "Destroy" Book Spec

Saturday, April 13, 13

Page 56: Rails Intro & Tutorial

Task 8: Refactor Routes

Saturday, April 13, 13

Page 57: Rails Intro & Tutorial

Task 9: Refactor Views

Saturday, April 13, 13

Page 58: Rails Intro & Tutorial

Task 10: Scaffold the Category

Saturday, April 13, 13

Page 59: Rails Intro & Tutorial

$ rails generate model Category name:string

$ rake db:migrate

$ rails console

> Category.column_names

Saturday, April 13, 13

Page 60: Rails Intro & Tutorial

Task 11: Apply Models' Associations

Saturday, April 13, 13

Page 61: Rails Intro & Tutorial

class Category < ActiveRecord::Base

has_many :books

end

class Book < ActiveRecord::Base

belongs_to :category

end

Saturday, April 13, 13

Page 62: Rails Intro & Tutorial

$ rails generate migration add_category_id_to_books category_id:integer:index

$ rake db:migrate

Saturday, April 13, 13

Page 63: Rails Intro & Tutorial

Task 12: Validate Inputs

Saturday, April 13, 13

Page 64: Rails Intro & Tutorial

class Book < ActiveRecord::Base

belongs_to :category

validates_presence_of :category_id,

:author,

:title

end

Saturday, April 13, 13

Page 65: Rails Intro & Tutorial

Task 13: Decorate with Twitter Bootstrap

Saturday, April 13, 13

Page 66: Rails Intro & Tutorial

Task 14: Deploy to Heroku

Saturday, April 13, 13

Page 67: Rails Intro & Tutorial

Assignments

Saturday, April 13, 13

Page 68: Rails Intro & Tutorial

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

Page 69: Rails Intro & Tutorial

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