This Guide is based on Rails 3.1. Some of the code shown here will not work in earlier versions of Rails.
This guide is designed for beginners who want to get started with a Rails application from scratch. It does not assume that you have any prior experience with Rails. However, to get the most out of it, you need to have some prerequisites installed:
- The Ruby language version 1.8.7 or higher
Note that Ruby 1.8.7 p248 and p249 have marshaling bugs that crash Rails 3.0. Ruby Enterprise Edition have these fixed since release 1.8.7-2010.02 though. On the 1.9 front, Ruby 1.9.1 is not usable because it outright segfaults on Rails 3.0, so if you want to use Rails 3 with 1.9.x jump on 1.9.2 for smooth sailing.
- The RubyGems packaging system
- If you want to learn more about RubyGems, please read the RubyGems User Guide
- A working installation of the SQLite3 Database
Rails is a web application framework running on the Ruby programming language. If you have no prior experience with Ruby, you will find a very steep learning curve diving straight into Rails. There are some good free resources on the internet for learning Ruby, including:
Also, the example code for this guide is available in the rails github:https://github.com/rails/rails repository in rails/railties/guides/code/getting_started.
2 What is Rails?This section goes into the background and philosophy of the Rails framework in detail. You can safely skip this section and come back to it at a later time. Section 3 starts you on the path to creating your first Rails application.
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 is opinionated software. It makes the assumption that there is a “best” way to do things, and it’s designed to encourage that way – and in some cases to discourage alternatives. If you learn “The Rails Way” you’ll probably discover a tremendous increase in productivity. If you persist in bringing old habits from other languages to your Rails development, and trying to use patterns you learned elsewhere, you may have a less happy experience.
The Rails philosophy includes several guiding principles:
- DRY – “Don’t Repeat Yourself” – suggests that writing the same code over and over again is a bad thing.
- Convention Over Configuration – means that Rails makes assumptions about what you want to do and how you’re going to do it, rather than requiring you to specify every little thing through endless configuration files.
- REST is the best pattern for web applications – organizing your application around resources and standard HTTP verbs is the fastest way to go.
At the core of Rails is the Model, View, Controller architecture, usually just called MVC. MVCbenefits include:
- Isolation of business logic from the user interface
- Ease of keeping code DRY
- Making it clear where different types of code belong for easier maintenance
A model represents the information (data) of the application and the rules to manipulate that data. In the case of Rails, models are primarily used for managing the rules of interaction with a corresponding database table. In most cases, each table in your database will correspond to one model in your application. The bulk of your application’s business logic will be concentrated in the models.
2.1.2 ViewsViews represent the user interface of your application. In Rails, views are often HTML files with embedded Ruby code that perform tasks related solely to the presentation of the data. Views handle the job of providing data to the web browser or other tool that is used to make requests from your application.
2.1.3 ControllersControllers provide the “glue” between models and views. In Rails, controllers are responsible for processing the incoming requests from the web browser, interrogating the models for data, and passing that data on to the views for presentation.
2.2 The Components of RailsRails ships as many individual components. Each of these components are briefly explained below. If you are new to Rails, as you read this section, don’t get hung up on the details of each component, as they will be explained in further detail later. For instance, we will bring up Rack applications, but you don’t need to know anything about them to continue with this guide.
- Action Pack
- Action Controller
- Action Dispatch
- Action View
- Action Mailer
- Active Model
- Active Record
- Active Resource
- Active Support
- Railties
Action Pack is a single gem that contains Action Controller, Action View and Action Dispatch. The “VC” part of “MVC”.
2.2.1.1 Action ControllerAction Controller is the component that manages the controllers in a Rails application. The Action Controller framework processes incoming requests to a Rails application, extracts parameters, and dispatches them to the intended action. Services provided by Action Controller include session management, template rendering, and redirect management.
2.2.1.2 Action ViewAction View manages the views of your Rails application. It can create both HTML and XML output by default. Action View manages rendering templates, including nested and partial templates, and includes built-in AJAX support. View templates are covered in more detail in another guide calledLayouts and Rendering.
2.2.1.3 Action DispatchAction Dispatch handles routing of web requests and dispatches them as you want, either to your application or any other Rack application. Rack applications are a more advanced topic and are covered in a separate guide called Rails on Rack.
2.2.2 Action MailerAction Mailer is a framework for building e-mail services. You can use Action Mailer to receive and process incoming email and send simple plain text or complex multipart emails based on flexible templates.
2.2.3 Active ModelActive Model provides a defined interface between the Action Pack gem services and Object Relationship Mapping gems such as Active Record. Active Model allows Rails to utilize other ORMframeworks in place of Active Record if your application needs this.
2.2.4 Active RecordActive Record is the base for the models in a Rails application. It provides database independence, basic CRUD functionality, advanced finding capabilities, and the ability to relate models to one another, among other services.
2.2.5 Active ResourceActive Resource provides a framework for managing the connection between business objects and RESTful web services. It implements a way to map web-based resources to local objects with CRUDsemantics.
2.2.6 Active SupportActive Support is an extensive collection of utility classes and standard Ruby library extensions that are used in Rails, both by the core code and by your applications.
2.2.7 RailtiesRailties is the core Rails code that builds new Rails applications and glues the various frameworks and plugins together in any Rails application.
2.3 RESTRest stands for Representational State Transfer and is the foundation of the RESTful architecture. This is generally considered to be Roy Fielding’s doctoral thesis, Architectural Styles and the Design of Network-based Software Architectures. While you can read through the thesis, REST in terms of Rails boils down to two main principles:
- Using resource identifiers such as URLs to represent resources.
- Transferring representations of the state of that resource between system components.
For example, the following HTTP request:
DELETE /photos/17
would be understood to refer to a photo resource with the ID of 17, and to indicate a desired action – deleting that resource. REST is a natural style for the architecture of web applications, and Rails hooks into this shielding you from many of the RESTful complexities and browser quirks.
If you’d like more details on REST as an architectural style, these resources are more approachable than Fielding’s thesis:
- A Brief Introduction to REST by Stefan Tilkov
- An Introduction to REST (video tutorial) by Joe Gregorio
- Representational State Transfer article in Wikipedia
- How to GET a Cup of Coffee by Jim Webber, Savas Parastatidis & Ian Robinson
The best way to use this guide is to follow each step as it happens, no code or step needed to make this example application has been left out, so you can literally follow along step by step. You can get the complete code here.
By following along with this guide, you’ll create a Rails project called blog, a (very) simple weblog. Before you can start building the application, you need to make sure that you have Rails itself installed.
The examples below use # and $ to denote terminal prompts. If you are using Windows, your prompt will look something like c:\source_code>
In most cases, the easiest way to install Rails is to take advantage of RubyGems:
If you’re working on Windows, you can quickly install Ruby and Rails with Rails Installer.
To verify that you have everything installed correctly, you should be able to run the following:
If it says something like “Rails 3.1.3” you are ready to continue.
3.2 Creating the Blog ApplicationTo begin, open a terminal, navigate to a folder where you have rights to create files, and type:
This will create a Rails application called Blog in a directory called blog.
You can see all of the switches that the Rails application builder accepts by running rails new -h.
After you create the blog application, switch to its folder to continue work directly in that application:
The ‘rails new blog’ command we ran above created a folder in your working directory called blog. The blog folder has a number of auto-generated folders that make up the structure of a Rails application. Most of the work in this tutorial will happen in the app/ folder, but here’s a basic rundown on the function of each of the files and folders that Rails created by default:
File/Folder | Purpose |
---|---|
app/ | Contains the controllers, models, views and assets for your application. You’ll focus on this folder for the remainder of this guide. |
config/ | Configure your application’s runtime rules, 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. |
doc/ | In-depth documentation for your application. |
Gemfile Gemfile.lock | These files allow you to specify what gem dependencies are needed for your Rails application. |
lib/ | Extended modules for your application. |
log/ | Application log files. |
public/ | The only folder seen to the world as-is. Contains the 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 | 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. |
script/ | Contains the rails script that starts your app and can contain other scripts you use to deploy or run your application. |
test/ | Unit tests, fixtures, and other test apparatus. These are covered in Testing Rails Applications |
tmp/ | Temporary files |
vendor/ | A place for all third-party code. In a typical Rails application, this includes Ruby Gems, the Rails source code (if you optionally install it into your project) and plugins containing additional prepackaged functionality. |
Just about every Rails application will interact with a database. The database to use is specified in a configuration file, config/database.yml. If you open this file in a new Rails application, you’ll see a default database configured to use SQLite3. The file contains sections for three different environments in which Rails can run by default:
- The development environment is used on your development/local computer as you interact manually with the application.
- The test environment is used when running automated tests.
- The production environment is used when you deploy your application for the world to use.
You don’t have to update the database configurations manually. If you look at the options of the application generator, you will see that one of the options is named —database. This option allows you to choose an adapter from a list of the most used relational databases. You can even run the generator repeatedly: cd .. && rails new blog —database=mysql. When you confirm the overwriting of the config/database.yml file, your application will be configured for MySQL instead of SQLite. Detailed examples of the common database connections are below.
Rails comes with built-in support for SQLite3, which is a lightweight serverless database application. While a busy production environment may overload SQLite, it works well for development and testing. Rails defaults to using an SQLite database when creating a new project, but you can always change it later.
Here’s the section of the default configuration file (config/database.yml) with connection information for the development environment:
In this guide we are using an SQLite3 database for data storage, because it is a zero configuration database that just works. Rails also supports MySQL and PostgreSQL “out of the box”, and has plugins for many database systems. If you are using a database in a production environment Rails most likely has an adapter for it.
If you choose to use MySQL instead of the shipped SQLite3 database, yourconfig/database.yml will look a little different. Here’s the development section:
If your development computer’s MySQL installation includes a root user with an empty password, this configuration should work for you. Otherwise, change the username and password in thedevelopment section as appropriate.
3.3.3 Configuring a PostgreSQL DatabaseIf you choose to use PostgreSQL, your config/database.yml will be customized to use PostgreSQL databases:
If you choose to use SQLite3 and are using JRuby, your config/database.yml will look a little different. Here’s the development section:
If you choose to use MySQL and are using JRuby, your config/database.yml will look a little different. Here’s the development section:
Finally if you choose to use PostgreSQL and are using JRuby, your config/database.yml will look a little different. Here’s the development section:
Change the username and password in the development section as appropriate.
3.4 Creating the DatabaseNow that you have your database configured, it’s time to have Rails create an empty database for you. You can do this by running a rake command:
This will create your development and test SQLite3 databases inside the db/ folder.
Rake is a general-purpose command-runner that Rails uses for many things. You can see the list of available rake commands in your application by running rake -T.
One of the traditional places to start with a new language is by getting some text up on screen quickly. To do this, you need to get your Rails application server running.
4.1 Starting up the Web ServerYou actually have a functional Rails application already. To see it, you need to start a web server on your development machine. You can do this by running:
Compiling CoffeeScript to JavaScript requires a JavaScript runtime and the absence of a runtime will give you an execjs error. Usually Mac OS X and Windows come with a JavaScript runtime installed. therubyracer and therubyrhino are the commonly used runtimes for Ruby and JRuby respectively. You can also investigate a list of runtimes atExecJS.
This will fire up an instance of the WEBrick web server by default (Rails can also use several other web servers). To see your application in action, open a browser window and navigate tohttp://localhost:3000. You should see Rails’ default information page:
http://edgeguides.rubyonrails.org/getting_started.html
测试窝什么时候能上传代码和附件就更好了。