Rails Basics(Rails基础)

本文翻译自SUN官方文档

What is and Why Ruby on Rails (RoR)? 
 
What Is “Ruby on Rails”?
A full-stack MVC web development framework
一个MVC的web开发框架
Written in Ruby
Ruby编写
First released in 2004 by David Heinemeier Hansson
由David Heinemeier Hansson在2004年发布第一个版本
Gaining popularity
更加流行
 
 “Ruby on Rails” MVC

 

“Ruby on Rails” Principles
“Ruby on Rails”的准测
Convention over configuration
约定更重于配置
  Why punish the common cases?
    Encourages standard practices
    鼓励标准化
    Everything simpler and smaller
    每件事情更加简单而小型化
  Don’t Repeat Yourself (DRY)
    Framework written around minimizing repetition
    这个框架减少重复劳动
    Repetitive code harmful to adaptability
    重复性代码有害适用性
  Agile development environment
    No recompile, deploy, restart cycles
    没有编译,部署,重启环节
    Simple tools to generate code quickly
    简单的工具高效产生代码
    Testing built into the framework
    由测试驱动


Step By Step Process of Building “Hello World” Rails Application
一步一步搭建“Hello World”的Rails应用
Steps to Follow:
  1. Create “Ruby on Rails” project - Rails generates directory structure    Rails自动产生目录结构
  2. Create Database (using Rake)    自动创建数据库
  3. Create Models (through Rails Generator)    自动创建模型
  4. Create Database Tables (using Migration)    自动创建数据表
  5. Create Controllers (through Rails Generator)    自动创建控制器
  6. Create Views    创建视图
  7. Set URL Routing - Map URL to controller and action    映射URL到控制器和action

Demo: Building “Hello World” Rails Application Step by Step.

1. Create “Ruby on Rails” Project
创建“Ruby on Rails”工程
The directory structure along with boilerplate files of the application is created
目录结构被自动创建


Directory Structure of a Rails Application
When you ask NetBeans to create a Rails project  - internally NetBeans uses the rails' helper script -, it creates the entire directory structure for your application.
netbeans会自动创建Rails的目录结构
    The boiler plate files are also created
    The names of the directories and files are the same for all Rails projects
Rails knows where to find things it needs within this structure, so you don't have to tell it explicitly.
Rails知道如何从这种结构里找到它需要的东西,你不必明确指明。

Directory Structure of a Rails Application
app: Holds all the code that's specific to this particular application.
app:控制这个项目专属的代码
  1. app/controllers: Holds controllers that should be named like hello_controller.rb for automated URL mapping. All controllers should descend from ApplicationController which itself descends from ActionController::Base.    app/controllers:控制器应该被命名如hello_controller.rb,这样就能自动映射URL。
  2. app/models: Holds models that should be named like message.rb. Most models will descend from ActiveRecord::Base.    app/models:模型应该被命名为message.rb。
  3. app/views: Holds the template files for the view that should be named like hello/say_hello.rhtml for the HelloController#say_hello action.     app/views:视图的模板文件应该被命名为hello/say_hello.rhtml
  4. app/views/layouts: Holds the template files for layouts to be used with views. This models the common header/footer method of wrapping views. In your views, define a layout using the <tt>layout :default</tt> and create a file named default.rhtml. Inside default.rhtml, call <% yield %> to render the view using this layout.
  5. app/helpers: Holds view helpers that should be named like hello_helper.rb. These are generated for you automatically when using script/generate (Generator) for controllers. Helpers can be used to wrap functionality for your views into methods.
config: Holds configuration files for the Rails environment, the routing map, the database, and other dependencies.
config:控制Rails环境的配置文件
config/environments
config/initializers
boot.rb
database.yml
environment.rb
routes.rb


Learning Point: Environments

What is an Environment?
Rails provides the concept of environments - development, test, production
Rails提供环境的概念 - 开发,测试,产品
As a default, different database is going to be used for different environment.
默认情况下,不同的数据将被用于不用的环境、
    Therefore each environment has its own database connection settings.
    因此,不同的环境有自己独立数据联接设置
It is easy to add custom environments
添加环境是很方便的
    For example, staging server environment
    例如,添加server环境
Rails always runs in only one environment
Rails只能在一个环境里运行
    Dictated by ENV['RAILS_ENV'] (same as RAILS_ENV)

config/database.yml
  1. development:
  2.   adapter: mysql
  3.   encoding: utf8
  4.   database: helloname_development
  5.   username: root
  6.   password:
  7.   host: localhost
  8. test:
  9.   adapter: mysql
  10.   encoding: utf8
  11.   database: helloname_test
  12.   username: root
  13.   password:
  14.   host: localhost

2. Create Database using “Rake”
Creating Database
    Creating and dropping of databases are done using “Rake”    用Rake创建和删除数据库


After create rake task is performed, <project_name>_development database, for example, helloworld_development is created


Learning Point: What is Rake?
What is “Rake”?
  1. Rake is a build language for Ruby.
  2. Rails uses Rake to automate several tasks such as creating and dropping databases, running tests, and updating Rails support files.
  3. Rake lets you define a dependency tree of tasks to be executed
How does “Rake” Work?
  1. Rake tasks are loaded from the file Rakefile
  2. Rails rake tasks are under <project-name>/lib/tasks
  3. You can put your custom tasks under lib/tasks
Useful Rake Tasks
db:migrate
db:sessions:create
doc:app
doc:rails
log:clear
rails:freeze:gems
rails:freeze:edge
rails:update
:test
:stats


3. Create a Model through “Generator”
What is a Model?
    In the context of MVC pattern, a Model represents domain objects such as message, school, product, etc.  A model has attributes and methods.
        The attributes represents the characteristics of the domain object, for example, a message model might have length, creator as attributes.  
        The methods in a model contains some business logic.  
    Most models have corresponding database tables.  For example, a message model will have messages table.
    Most model classes are ActiveRecord type

Creating a Model using Generator



Files That Are Created
app/models/message.rb (Model file)
  1. Models/messages.rb in logical view
  2. A file that holds the methods for the Message model.
test/unit/message_test.rb
  1. Unit Tests/message_test.rb in logical view
  2. A unit test for checking the Message model.
test/fixtures/messages.yml
  1. Test Fixtures/messages.yml in logical view
  2. A test fixture for populating the model.
db/migrate/migrate/001_create_messages.rb
  1. Database Migrations/migrate/001_create_messages.rb in logical view
  2. A migration file for defining the initial structure of the database.

Model Class Example
Message mode in messages.rb file
  1. class Message < ActiveRecord::Base
  2. end


Learning Point: What is Generator?
What is “Generator”?
You can often avoid writing boilerplate code by using the built-in generator scripts of Rails to create it for you.
模板的代码可以由Rails脚本完成
This leaves you with more time to concentrate on the code that really matters--your business logic.
这可以使你将更多的精力放在那些真正有意义的业务逻辑代码上

Leaning Point:What is Rails Console?
The Rails console gives you access to your Rails Environment, for example, you can interact with the domain models of your application as if the  application is actually running.
    Things you can do include performing find operations or creating a new active record object and then saving it to the database.
A great tool for impromptu testing
NetBeans runs a script to start Rails Console


Leaning Point: What is Rails Script?
Script
NetBeans runs Rails Script internally
    You can run the Script at the commandline
Useful scripts
console
generate
plugin
server


4. Create Database Tables using Migration
You are going to create a database table (in a previously created database) through migration
    You also use migration for any change you are going to make in the schema - adding a new column, for example
When you create a Model, the first version of the migration file is automatically created
    db/migrate/migrate/001_create_messages.rb, which defines initial structure of the table
  1. class CreateMessages < ActiveRecord::Migration
  2.   def self.up
  3.     create_table :messages do |t|
  4.       t.string :greeting
  5.       t.timestamps
  6.     end
  7.   end
Performing Migration


Leaning Point: What is Migration?
Migrations can manage the evolution of a schema.
It's a solution to the common problem of adding a field to make a new feature work in your local database, but being unsure of how to push that change to other developers and to the production server.
With migrations, you can describe the transformations in self-contained classes that can be checked into version control systems and executed against another database that might be one, two, or five versions behind. 

5. Create a Controller
  1. Action Controllers are the core of a web request in Rails.
  2. They are made up of one or more actions that are executed on request and then either render a template or redirect to another action.
  3. An action is defined as a public method on the controller, which will automatically be made accessible to the web-server through Rails Routes.
  4. You are going to create a controller using Generator


Example: HelloController
Controller contains actions, which are defined with def
  1. class HelloController < ApplicationController
  2.   def say_hello
  3.     @hello = Message.new(:greeting => "Hello World!")
  4.   end
  5. end


6. Write a View
What is a View?
  1. View is represented by a set of templates that get displayed. 
  2. Templates share data with controllers through mutually accessible variables. 
  3. A template can be either in the form of *.rhtml or *.erb file.  -  The *.erb file is searched first by Rails. If there is no *.erb file, then *.rhtml file is used.
  4. RHTML file is created under the directory of /app/views/<controller>

  1. say_hello.rhtml
  2. My greeting message is <%= @hello.greeting %>
  3. <br/>
  4. The current time is <%= Time.now %>


7. Set URL Routing
URL Routing
The Rails routing facility is pure Ruby code that even allows you to use regular expressions.
    Because Rails does not use the web server's URL mapping, your custom URL mapping will work the same on every web server.
    configuration/routes.rb file contains the routing setting

routes.rb
  1. ActionController::Routing::Routes.draw do |map|
  2.   
  3.   map.root :controller => "hello"
  4.   # Install the default routes as the lowest priority.
  5.   map.connect ':controller/:action/:id'
  6.   map.connect ':controller/:action/:id.:format'
  7. end

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值