Ruby on Rails Tutorial

  • Published on
    27-May-2015

  • View
    608

  • Download
    1

Embed Size (px)

DESCRIPTION

Ruby on Rails Tutorial

Transcript

  • Ruby on RailsTutorial

    1

  • Ruby 2.0.0

    Rails 4.0.0

    Bundler 1.3.5

    SQLite 3.7.2

    2

  • Rails

    % mkdir -p tutorial% cd tutorial% bundle init% vi Gemfile% bundle install --path vendor/bundle

    Gemfilesource "https://rubygems.org"

    gem "rails"

    3

    https://rubygems.orghttps://rubygems.org
  • 1

    % bundle exec rails new . --skip-bundle

    conflict GemfileOverwrite /path/to/tutorial/Gemfile? (enter "h" for help) [Ynaqdh] Enter()

    -T test/unit

    -d mysql/postgresqlSQLite

    --skip-bundle bundle init

    4

  • 2

    % vi Gemfile% bundle

    # See https://github.com/sstephenson/execjs#readme for more supported runtimes# gem 'therubyracer', platforms: :ruby

    Gemfile

    % export PATH=`pwd`/bin:$PATH% rails -v

    5

    https://github.com/sstephenson/execjs#readmehttps://github.com/sstephenson/execjs#readme
  • app

    app

    assets image/stylesheet/javascript

    appcontrollers

    app helpers appmailers

    app

    models

    app

    views bin bundle/rails/rakebundle/rails/rake

    config db /SQLite DB/SQLite DBlib /Rake/Rakelog

    public WebDocumentRootWebDocumentRoottest (RSpecspec)(RSpecspec)tmp TempTemp

    vendor 6

  • rails/rake

    rails server WEBrickrails console Railsrails dbconsole DBrails runner Rails

    rake db:create rake db:migrate rake db:rollback rake routes rake assets:precompile

    7

  • % rails s

    8

  • Scaffold% rails generate scaffold blog title:string body:text% rake db:migrate

    CRUDmodel/scaffold

    `rake db:migrate`DB

    assets/controller/helper/model/view

    9

  • % rails g model : :

    % rails g controller

    % rails g migration

    db/migrate/YYYYmmddHHMMSS_task.rb`rake db:migrate`/

    assets/controller/helper/view

    modelstring/text/integer/float/boolean/date/time/timestampDBDB

    10

  • db/migrate/

    `rake db:migrate`DB

    `rake db:rollback`

    schema_migrations

    class CreateBlogs < ActiveRecord::Migration def change create_table :blogs do |t| t.string :title t.text :body

    t.timestamps end endend

    11

  • router(routes.rb)

    DBServer

    controllers(controllers/*.rb)

    models(models/*.rb)

    views(views/*/

    *.html.erb)

    request routing

    sql

    response

    12

  • app/models/blog.rb

    class Blog < ActiveRecord::Baseend

    //DB

    % rails c> blog = Blog.new> blog.title = "test title"> blog.body = "test body"> blog.save # blogs> blogs = Blog.all # blogs> blogs.each {|b| puts b.title} # title> blog = Blog.find(1) # blogsid1> puts blog.title # title> blog.destroy # blogs

    13

  • 1

    Tutorial::Application.routes.draw do resources :blogsend

    config/routes.rb

    % rake routes Prefix Verb URI Pattern Controller#Action blogs GET /blogs(.:format) blogs#index POST /blogs(.:format) blogs#create new_blog GET /blogs/new(.:format) blogs#newedit_blog GET /blogs/:id/edit(.:format) blogs#edit blog GET /blogs/:id(.:format) blogs#show PATCH /blogs/:id(.:format) blogs#update PUT /blogs/:id(.:format) blogs#update DELETE /blogs/:id(.:format) blogs#destroy

    14

  • 2

    Tutorial::Application.routes.draw do controller :blogs do # HTTPMethod URI, to: ExecMethod, as: :Prefix # GET /index => BlogsController#index (index_path) get :index, to: :index, as: :index

    # POST /create => BlogsController#create (create_path) post :create, to: :create, as: :create

    # GET / => BlogsController#root (root_path) get :root, to: "blogs#root" endend

    15

  • 1

    class BlogsController < ApplicationController before_action :set_blog, only: [:show, :edit, :update, :destroy]

    def index @blogs = Blog.all end

    def new @blog = Blog.new end

    private def set_blog @blog = Blog.find(params[:id]) end

    def blog_params params.require(:blog).permit(:title, :body) endend

    app/controller/blogs_controller.rb

    view16

  • 2

    #index@blogsblogsview

    #new@blogBlogview

    #showbefore_actionset_blogview

    #editshowbefore_actionset_blogview

    17

  • 3class BlogsController < ApplicationController def create @blog = Blog.new(blog_params)

    respond_to do |format| if @blog.save format.html { redirect_to @blog, notice: 'Blog was successfully created.' } format.json { render action: 'show', status: :created, location: @blog } else format.html { render action: 'new' } format.json { render json: @blog.errors, status: :unprocessable_entity } end end endend

    Blogstrong parameter@blog@blog.save(DB)newview

    18

  • 4

    class BlogsController < ApplicationController def update respond_to do |format| if @blog.update(blog_params) format.html { redirect_to @blog, notice: 'Blog was successfully updated.' } format.json { head :no_content } else format.html { render action: 'edit' } format.json { render json: @blog.errors, status: :unprocessable_entity } end end endend

    before_actionset_blog@blog.updatecreatestrong parametereditview

    19

  • 5class BlogsController < ApplicationController def destroy @blog.destroy respond_to do |format| format.html { redirect_to blogs_url } format.json { head :no_content } end endend

    before_actionset_blog@blog.destroy

    `respond_to {|format| ...}`format

    20

  • 1

    Tutorial true %> true %>

    HTMLlayoutviewHTMLruby()()

    app/views/layouts/application.html.erb

    21

  • 2

    Editing blog

    |

    `render``redirect_to`app/views//.html.erb(formathtml)edit.html.erb`render`

    app/views/blogs/edit.html.erb

    22

  • 1

    % vi Gemfile% bundle

    # gem "passwd"

    Gemfile

    Gemfile`require`(grouprequirefalse)

    2.bundle/configbundle

    23

  • 2

    % rails g controller sessions

    /Sessions

    Tutorial::Application.routes.draw do resources :blogs

    # controller :sessions do get :login, to: :new, as: :new_session post :login, to: :create, as: :create_session get :logout, to: :destroy, as: :delete_session endend

    config/routes.rb

    % rake routes... new_session GET /login(.:format) sessions#newcreate_session POST /login(.:format) sessions#createdelete_session GET /logout(.:format) sessions#destroy

    24

  • 3

    ()app/views/sessions/new.html.erb

    class SessionsController < ApplicationController def create render text: "login" end def destroy render text: "logout" endend

    SessionsControllercreate/destroyapp/controllers/sessions_controller.rb

    25

  • 4

    % rails g model user email:string salt:string password:string% rake db:migrate

    class User < ActiveRecord::Base include Passwd::ActiveRecord define_columnend

    Userapp/models/user.rb

    % rails c> user = User.new> user.email = "foo@example.com"> user.set_password("secret")> user.save> puts password

    26

    mailto:foo@example.commailto:foo@example.com
  • 5

    class SessionsController < ApplicationController def create @user = User.authenticate(params[:email], params[:password]) if @user session[:user] = @user.id redirect_to blogs_path else flash.now[:alert] = "Email or password is incorrect." render action: :new end end def destroy session[:user] = nil redirect_to blogs_path endend

    /app/controllers/session_controller.rb

    27

  • 1

    class ApplicationController < ActionController::Base protect_from_forgery with: :exception

    # def require_logged_in if session[:user].present? begin @user = User.find(session[:user]) rescue ActiveRecord::RecordNotFound reset_session end end redirect_to create_session_path unless @user endend

    ApplicationControllerapp/controllers/application_controller.rb

    application_controller.rb

    28

  • 2

    class BlogsController < ApplicationController before_action :set_blog, only: [:show, :edit, :update, :destroy] # before_action :require_logged_in, only: [:new, :edit, :create, :update, :destroy]

    ...end

    new/edit/create/update/destroy

    before_action`require_logged_in`

    29