Ruby on Rails 初次冲浪体验

Posted 袁慎建@ThoughtWorks

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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应用开发更加容易。它可以让你写更少的代码来完成其他语言和框架所不能完成的工作。有过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

  • 生成工程的目录结构,此处英文较为通俗,建议读一读,心里稍微有个数。

    File/FolderPurpose
    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.ruRack configuration for Rack based servers used to start the application.
    db/Contains your current database schema, as well as the database migrations.
    Gemfile Gemfile.lockThese 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.
    RakefileThis 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.rdocThis 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

……

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

以上是关于Ruby on Rails 初次冲浪体验的主要内容,如果未能解决你的问题,请参考以下文章

如何在本地网络上托管 Ruby on Rails 应用程序,以便多人可以访问它?

思考Ruby On Rails的底层代码(Ruby on Rails 開發秘籍 | Ruby on Rails 快速入門)

ruby on rails如何安装

ruby on rails - 问题捆绑安装nokogiri 1.7.2 on ruby on rails 4.x.

Ruby on Rails入门篇

markdown [rails:devise] Ruby on Rails的身份验证gem。 #ruby #rails