Ruby on Rails 初次冲浪体验

为了更好的阅读体验,欢迎訪问 作者博客原文


Rails is a web application development framework written in the Ruby language. It is designed to make programming web applications easier by making assumptions about what every developer needs to get started. It allows you to write less code while accomplishing more than many other languages and frameworks. Experienced Rails developers also report that it makes web application development more fun.

Rails是一个用Ruby编写的Web应用开发框架。

它的设计目标是通过预先提供开发者最開始须要的基础设施。从而让Web应用开发更加easy。

它能够让你写更少的代码来完毕其它语言和框架所不能完毕的工作。有过Rail开发经验的人都说它能让web应用开发变得更有趣。


环境准备

  1. Ruby,版本号 >= 1.9.3。Ruby安装
  2. RubyGems包管理系统, 跟Ruby@1.9以上版本号一起安装。
  3. SQLite3数据库.SQLite3安装
 $ ruby -v
 ruby 2.2.3p173

 $ gem -v
 2.4.8

 $ sqlite3 --version
 3.8.10.2

心里准备

此文档篇幅着实太长,单从文件夹来看就可能被吓退三尺。

实践是最好的学习方式,你不必太操心,此文章乃纯干货,通篇在编码实践,让你在实践中感受Rails的魅力。它比一个简单的Hello World更加有趣以及充满了挑战性。

它是一个循序渐进的过程,能让你在每一小步都能获得信心和成就感。同一时候,请相信我。在你到达终点前。你都不必纠结于当中的实现细节。

而当你敲下最后一个回车的时候,你对Rail的感觉或许会从陌生人到恋人。开启愉快的Rails之旅吧,美好的风景在后面。


创建Rails项目

安装Rails

$ gem install rails

$ rails -v  
Rails 4.2.5

创建一个blog应用

$ rails new blog
$ cd blog

  • 生成project的文件夹结构,此处英文较为通俗,建议读一读,心里略微有个数。

    File/Folder Purpose
    app/ Contains the controllers, models, views, helpers, mailers and assets for your application. You’ll focus on this folder for the remainder of this guide.
    bin/ Contains the rails script that starts your app and can contain other scripts you use to setup, deploy or run your application.
    config/ Configure your application’s routes, database, and more. This is covered in more detail in Configuring Rails Applications.
    config.ru Rack configuration for Rack based servers used to start the application.
    db/ Contains your current database schema, as well as the database migrations.
    Gemfile Gemfile.lock These files allow you to specify what gem dependencies are needed for your Rails application. These files are used by the Bundler gem. For more information about Bundler, see the Bundler website.
    lib/ Extended modules for your application.
    log/ Application log files.
    public/ The only folder seen by the world as-is. Contains static files and compiled assets.
    Rakefile This file locates and loads tasks that can be run from the command line. The task definitions are defined throughout the components of Rails. Rather than changing Rakefile, you should add your own tasks by adding files to the lib/tasks directory of your application.
    README.rdoc This is a brief instruction manual for your application. You should edit this file to tell others what your application does, how to set it up, and so on.
    test/ Unit tests, fixtures, and other test apparatus. These are covered in Testing Rails Applications.
    tmp/ Temporary files (like cache, pid, and session files).
    vendor/ A place for all third-party code. In a typical Rails application this includes vendored gems.

Hello, Rails!

启动Rails服务

$ rails server

$ rails server
    => Booting WEBrick
    => Rails 4.2.5 application starting in development on http://localhost:3000
    => Run `rails server -h` for more startup options
    => Ctrl-C to shutdown server
    [2016-04-06 11:32:26] INFO  WEBrick 1.3.1
    [2016-04-06 11:32:26] INFO  ruby 2.2.3 (2015-08-18) [x86_64-darwin14]
    [2016-04-06 11:32:26] INFO  WEBrick::HTTPServer#start: pid=18756 port=3000

訪问Rails服务

打开你的浏览器,输入http://localhost:3000。会看到以下页面

这里写图片描写叙述


加入一个控制器

$ rails generate controller welcome index

$ rails generate controller welcome index
    create  app/controllers/welcome_controller.rb
    route  get 'welcome/index'
    invoke  erb
    create    app/views/welcome
    create    app/views/welcome/index.html.erb
    invoke  test_unit
    create    test/controllers/welcome_controller_test.rb
    invoke  helper
    create    app/helpers/welcome_helper.rb
    invoke    test_unit
    invoke  assets
    invoke    coffee
    create      app/assets/javascripts/welcome.coffee
    invoke    scss
    create      app/assets/stylesheets/welcome.scss 

以下是generator为你生成的两个重要的控制器和视图文件

  • app/controllers/welcome_controller.rb
  • app/views/welcome/index.html.erb.

index.html.erb文件内容替换成:<h1>Hello, Rails!</h1>


设置应用主页

打开路由配置文件config/routes.rb,加入内容root 'welcome#index'

Rails.application.routes.draw do
  root 'welcome#index'

  get 'welcome/index'

  # The priority is based upon order of creation:
  # first created -> highest priority.
  #
  # You can have the root of your site routed with "root"
  # root 'welcome#index'
  #
  # ...

让程序跑起来

加入Article资源

继续编辑路由配置文件config/routes.rb。加入内容resources :articles

Rails.application.routes.draw do

  resources :articles

  root 'welcome#index'
end

查看资源的RESTful API

$ rake routes

$ rake routes
       Prefix Verb   URI Pattern                  Controller#Action
         root GET    /                            welcome#index
     articles GET    /articles(.:format)          articles#index
              POST   /articles(.:format)          articles#create
  new_article GET    /articles/new(.:format)      articles#new
 edit_article GET    /articles/:id/edit(.:format) articles#edit
      article GET    /articles/:id(.:format)      articles#show
              PATCH  /articles/:id(.:format)      articles#update
              PUT    /articles/:id(.:format)      articles#update
              DELETE /articles/:id(.:format)      articles#destroy
welcome_index GET    /welcome/index(.:format)     welcome#index

Article资源加入控制器

$ rails generate controller articles

$ rails generate controller articles
      create  app/controllers/articles_controller.rb
      invoke  erb
      create    app/views/articles
      invoke  test_unit
      create    test/controllers/articles_controller_test.rb
      invoke  helper
      create    app/helpers/articles_helper.rb
      invoke    test_unit
      invoke  assets
      invoke    coffee
      create      app/assets/javascripts/articles.coffee
      invoke    scss
      create      app/assets/stylesheets/articles.scss

会生成articles_controller.rb控制器文件

class ArticlesController < ApplicationController
end

创建加入Article的表单视图

创建文件app/views/articles/new.html.erb,加入表单内容:

<h1>New Article</h1>
<%= form_for :article, url: articles_path do |f| %>
  <p>
    <%= f.label :title %><br>
    <%= f.text_field :title %>
  </p>

  <p>
    <%= f.label :text %><br>
    <%= f.text_area :text %>
  </p>

  <p>
    <%= f.submit %>
  </p>
<% end %>

訪问链接http://127.0.0.1:3000/articles/new

这里写图片描写叙述


Article加入create控制器方法

打开文件articles_controller.rb。加入create方法:

class ArticlesController < ApplicationController
  def new
  end

  def create
    render plain: params[:article].inspect
  end
end

此时提交表单之后,页面会显示:

{"title"=>"First article!", "text"=>"This is my first article."}`

创建一个Article数据库模型

$ rails generate model Article title:string text:text

……

为了更好的阅读体验,很多其它内容,欢迎訪问 作者博客原文

原文地址:https://www.cnblogs.com/lxjshuju/p/7281855.html