Ruby on rails actual Bible: Rails start walking

Rails start walking
There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies and the other way is to make it so complicated that there are no obvious deficiencies. - C.A.R. Hoare,
In this chapter, we will begin to introduce how to create a simple Hello program, World!, and CRUD application with the most fast way.
CRUD refers to the Create (Xin Zeng), Read (read), Update (update), Delete (delete) four basic ways of operating data.
In the last chapter, after installing Rails, you will get a rails command on the command line, the command can be an initial Rails project directory.
Begin to build your first Rails application
Please open a command line window (Terminal), and then find a directory for your Rails project, says projects.:
$ mkdir projects
$ cd projects
Then, enter the following command will establish a demo Rails project:
$ rails new demo
If there is a out of the directory is not demo but new, so that your Rails version is outdated, enter the rails -v to check the version of Rails must be 3 or above. If not, please return at the end of the chapter on implementation of gem install rails to install Rails 3.
You will see the following message shows the total added which files:
create README
create Rakefile
create .gitignore
create Gemfile
create app
create vendor/plugins
create vendor/plugins/.gitkeep
This establishes a demo directory, let us continue to:
$ cd demo
This directory contains a directory structure and file a Rails project will be used, we visit, input LS (Windows readers please enter DIR) shows the files in a directory:
File / directory and use
Set the Gemfile Rails application will use what Gems Kit
Project Description: the README application you can use to tell others your what is used, how to use etc.
Rakefile used to load can be ordered some Rake tasks for execution
app/ Controllers, Models and Views files, the following contents are mainly in this directory.
config/ The application configuration file, routing rules, set the database etc. Rack server configuration file used to start the application.
db/ The structure of the database
doc/ For your file
lib/ Put some custom Module class file
log/ Log log file applications
public/ Only you can see on the web directory, this is your drawing, JavaScript, CSS and other static files.
script/ Put the rails instruction and put the other script instruction
test/ Unit testing and integration testing program, fixtures
tmp/ A temporary file
vendor/ To put the third party code plug-in directory
Start server
Rails used a tool called Bundler which can help us to check for and install the Rails application all dependent suite, please input:
$ bundle install
You can just input bundle is bundle install. Every time want to modify the Gemfile file, will need to re execute the bundle
There will be
Fetching source index for
Your bundle is complete! Use `bundle show [gemname]` to see where a bundled gem is installed.
In the development of computer, we do not need to install Apache, IIS web server. Ruby itself provides a HTTP server can execute Rails, to start it, we open a command window, CD into the newly established Rails project directory and then enter the rails server:
$ cd projects/demo
$ rails server
The following message will appear:
=> Booting WEBrick
=> Rails 3.2.8 application starting in development on
=> Call with -d to detach
=> Ctrl-C to shutdown server
[2012-09-30 04:23:28] INFO WEBrick 1.3.1
[2012-09-30 04:23:28] INFO ruby 1.9.3 (2012-04-20) [x86_64-darwin12.1.0]
[2012-09-30 04:23:28] INFO WEBrick::HTTPServer#start: pid=18615 port=3000
Rails server can be abbreviated as rails s
The use of Ubuntu operating system's friend, if Could not find a JavaScript runtime error occurred when starting the server, please edit the Gemfile file with a gem'therubyracer', input bundle install to install this package, and then start a rails server. This is because in the Ubuntu operating system on the default without any JavaScript interpreter can be used for Rails. You can install Node.js or therubyracer is installed the Ruby suite to obtain the JavaScript interpreter.
Then open your browser to go, we can see the default home page Rails. The Welcome Aboard screen can confirm that the settings are correct, click the About your application 's environment hyperlink can see more environmental information.

To interrupt the server, please press Ctrl+C (if it does not work please try Ctrl+Z). In the development development mode, in addition to modify the config or vender directory under the file needs to be restarted, other modifications usually do not need to re start, modified files automatically reload. If production officially launched mode, modify any files must restart the server will have the effect.
The first Hello World!!
Let the program said Hello World! But a tradition we learn to write the program. We mentioned the Rails is the MVC framework, Hello World! Do not need to use the database, so as long as we write Controller and View, and make the routing assignment to the Controller, enter the following command would produce a welcome empty Controller file:
$ rails generate controller welcome
May be abbreviated to rails g controller welcome
Next add a setting in the routing file config/routes.rb:
Demo::Application.routes.draw do
get "welcome/say_hello" => "welcome#say"
# ...
Get this line to mean to such sites correspond to the welcome Controller say Action.
Edit app/controllers/welcome_controller.rb, add a say method:
class WelcomeController <ApplicationController
def say
If you are using Ruby 1.9 series, if there is a UTF-8 character program, for example in the text, then in the beginning of the file first line must be added # encoding: utf-8. Otherwise there will be invalid multibyte char (US-ASCII) exception error.
In Controller, an open function (public method) represents a Action, a Action corresponding to a HTTP request and response. Then we open a browser, you will see an error as follows:
Template is missing
Missing template welcome/say, application/say with {:handlers=>[:erb, :builder], :formats=>[:html], :locale=>[:en, :en]}. Searched in: * "/Users/ihower/rails/rails31/app/views"
This is because we are not ready to View file. Please add the app/views/welcome/say.html.erb file, in accordance with the practice of the directory name is Controller name, file name is Action name, the first report of the file name that this is a HTML file, second attached file name that this is ERb model (we will in a chapter View carefully introduce model). Edit the file contents are as follows:
<h1>Hello, World!</h1>
Then rearrange a browser, you will see the Hello, the World!.
Let us add a page and add links, edit the file config/routes.rb into a routing routing:
get "welcome" => "welcome#index"
This line to mean to such sites correspond to the welcome Controller index Action.
Edit the app/controllers/welcome_controller.rb accession
def index
The new app/views/welcome/index.html.erb content
<p>Hola! It's <%= %></p>
<p><%= link_to 'Hello!', welcome_say_hello_path %></p>
Time is a Ruby built-in time category, will output the current time. Link_to is the built-in Rails can output a hyperlink, and the welcome_say_hello_path will output /welcome/say_hello this web site. Auxiliary method that appears in the View referred to as Helper. Browse, see Hola! And Hello! Hyperlink.

Set home page
How will the website home page change to welcome#index? First of all, we will public/index.html this file removed, this is because the Rails will return any static file under the public directory. Then edit the config/routes.rb to open the following code:
root :to => "welcome#index"
Ruby single line comment is # well No.
This line to mean, the web site root directory guide to welcome Controller index Action. How do you set back to the home page links in the View? Edit the app/views/welcome/say.html.erb accession:
<p><%= link_to "Home", root_path %></p>
Setting and establishment of database
The operation of the database is a very basic function of dynamic web site, before writing a CRUD application, we must first set up the database. The database configuration file Rails is config/database.yml, if you open this file, the default setting is SQLite3. This document contains three different environmental settings, corresponding to three Rails execution environment:
, Development development model, when used in your development
, Test test model, used in the implementation of automatic test
, Production officially launched model, used in the actual on-line operation environment
Setting the SQLite3 database
The built-in Rails support SQLite3 this is a very lightweight non server database applications, the database is just a file. Large flow of officially launched although the environment is not suitable for SQLite, but used to develop and test is very easy to use. The default Rails also uses the SQLite3 database to set up a new project, the following is the default setting data config/database.yml:
# SQLite version 3.x
# gem install sqlite3
adapter: sqlite3
database: db/development.sqlite3
pool: 5
timeout: 5000
# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
adapter: sqlite3
database: db/test.sqlite3
pool: 5
timeout: 5000
adapter: sqlite3
database: db/production.sqlite3
pool: 5
timeout: 5000
The middle section comments tell you not to test database with production or development with a
The rest of the book are the use of SQLite3 database, because it does not need what settings you can use.
The YAML format is strict indentation (recommended for two blank), and colon must be followed by a space. We generally expected YAML value of string, so when is digital or multi line content, suggest quotes to avoid string parsing error. For example, password: " 123456". If there are no quotes, this string of numbers will be parsed into a Fixnum object rather than a string String.
Establish database
The database has been set, enter the following command allows Rails to create empty database:
$ bundle exec rake db:create
This will be in the db/ directory to create development and test SQLite3 file.
Rake is a command line tool for Ruby, you can enter the rake -T lists all the available commands. We will be in later chapters detail Rake.
Your first CRUD program
Rails scaffold scaffolding function will automatically generate a set of Model, Views and Controller code, complete a simple CRUD program for the display and use learning. Please input:
$ rails g scaffold person name:string bio:text birthday:date
Files generated by the simple explanation is as follows, the name of the Model note is in the singular person, and Controller according to RESTful practices are used in the plural. People:
db/migrate/20110517161435_create_people.rb used to create people database table Migration (your file name will have a different time)
app/models/Person.rb person model files
test/fixtures/People.yml used to fake the data test
app/controllers/People_controller.rb people controller files
app/views/people/Index.html.erb is used to display all the index pages
app/views/people/Edit.html.erb is used to edit the page
app/views/people/Show.html.erb is used to display a particular article page
app/views/people/New.html.erb is used to add the article page
app/views/people/_Form.html.erb is used to display and edit and add the form part (Partial) model
app/helpers/Helper people_helper.rb method can be used in the articles in Views
test/unit/Person_test.rb people model unit test
test/functional/Function test of people_controller_test.rb people controller
test/unit/helpers/People_helper_test.rb people helper unit test
config/Routes.rb set URL routing rules file, scaffold again this added a line of resources: People
app/assets/stylesheets/The style file scaffold.css.scss Scaffold scaffolding provided
app/assets/stylesheets/CSS style file people.css.scss people
app/assets/javascripts/ people JavaScript files
Although the scaffolding (scaffolding) can help you get started quickly, but can't produce perfect to meet the needs of the program code. Rails programmers have little experience using the default scaffolding generated code, but prefer to use Rails generator to produce Model and Controller files, and even customize its own scaffold program.
Scaffold generated by the program, there is a database migration file (database migration). The purpose of Migration is to create and modify database data table. Rails use the rake command to execute Migrations. The Migration file contains the Timestamp (time stamp chapter), to ensure that they can in accordance with the established time sequential execution.
Please enter the following command Migration:
$ bundle exec rake db:migrate
Rails then creates people data sheet:
== Createpeople: migrating ====================================================
-- create_table(:people)
-> 0.0019s
== Createpeople: migrated (0.0020s) ===========================================
Because the default is run in development mode, this command will set the specified by the config/database.yml development in that database.
Browsing can operate, very magical. However, there is no detail of the generated code, readers read later chapters, will understand.

Common errors
NoMethodError is very obvious, is that you have the wrong way, for example, in this case, the link_to to link_too. According to the error message you should be able to easily find which file in one line.

NameError is also very obvious, read a non-existent local variable will appear the following error:

SyntaxError: unexpected $end
SyntaxError plus unexpected $end, expecting keyword_end, it must be you less (or more) end keywords, def and do must have the corresponding end. Unfortunately Rails has no way to remind you is that a few (or more) end, wrong line number will tell you is the last line. If is really not very good looking, you can use ruby -w to perform error program, such as ruby -w app/controller/welcome_controller, this will open the Ruby warning model to obtain more accurate grammar error messages.

invalid multibyte char (US-ASCII)
Finally, the Ruby 1.9 can be: invalid multibyte char (US-ASCII), that you have a UTF-8 character in the source code (for example Chinese inside), you must declare the following notation in the file first can solve this problem, of course, the file format you unit must be the correct UTF-8 (no BOM mark):
# encoding: utf-8

Posted by Elsa at December 31, 2013 - 3:27 AM