第一章
1.在git中设置编辑器(用来编写比较多的评论)
$ git config --global core.editor "subl -w"
评论的时候,就不用git commit -m "XXX",忽略这里的-m,git会自动打开编辑器,在编辑器里面编辑评论内容
2.linux下删除文件夹
$ rm -rf app/controllers/
3.使用Git小技巧之一:在当前工作树中,没提交,想回到没做改动时候的版本(撤销本次修改)
$ git checkout -f
$ git status
# On branch master
4.创建新分支
$ git checkout -b modify-README Switched to a new branch 'modify-README' $ git branch master * modify-README
5.重命名命令:不算做是新文件
$ git mv README.rdoc README.md
$ sublime README.md(打开文件)
6.合并分支命令
$ git checkout master Switched to branch 'master' $ git merge modify-README Updating 34f06b7..2c92bef
7.删除分支
$ git branch -d modify-README Deleted branch modify-README (was 2c92bef).
8强制删除分支
$ git checkout -b topic-branch $ <really screw up the branch> $ git add . $ git commit -a -m "Major screw up" $ git checkout master $ git branch -D topic-branch
9.之前项目中,比较常用的一种分支控制(合并时,--no-ff,可以保存历史信息,gitk命令可以看起来很漂亮)
$ git checkout develop
Switch to branch ‘develop’
$ git merge –no-ff myfeature
Updating ea1b82a..05e9557
(Summary of changes)
$ git branch -d myfeature
Deleted branch myfeature (was 05e9557).
$ git push origin develop
上述代码中的–no-ff标记会使合并永远创建一个新的commit对象,即使该合并能以fast-forward的方式进行。这么做可以避免丢失特性分支存在的历史信息,同时也能清晰的展现一组commit一起构成一个特性。
10.远程部署到heroku
先在heroku创建一个新项目
$ heroku create --stack cedar
(The --stack cedar argument arranges to use the latest and greatest version of Heroku, called the Celadon Cedar Stack.)
然后用git push到heroku
$ git push heroku master
第二章
1.现阶段项目使用的gemfile
source 'https://rubygems.org'
gem 'rails', '3.2.8'
group :development do
gem 'sqlite3', '1.3.5'
end
# Gems used only for assets and not required
# in production environments by default.
group :assets do
gem 'sass-rails', '3.2.5'
gem 'coffee-rails', '3.2.2'
gem 'uglifier', '1.2.3'
end
gem 'jquery-rails', '2.0.2'
group :production do
gem 'pg', '0.12.2'
end
其中,安装pg是为了部署在heroku上,因为heroku不支持sqlite3。然后
$ bundle install --without production
3.使用脚手架
$ rails generate scaffold User name:string email:string
$ bundle exec rake db:migrate

- The browser issues a request for the /users URI.
- Rails routes /users to the
index
action in the Users controller. - The
index
action asks the User model to retrieve all users (User.all
). - The User model pulls all the users from the database.
- The User model returns the list of users to the controller.
- The controller captures the users in the
@users
variable, which is passed to theindex
view. - The view uses embedded Ruby to render the page as HTML.
- The controller passes the HTML back to the browser.3
6RESTFul.
HTTP request | URI | Action | Purpose |
---|---|---|---|
GET | /users | index | page to list all users |
GET | /users/1 | show | page to show user with id 1 |
GET | /users/new | new | page to make a new user |
POST | /users | create | create a new user |
GET | /users/1/edit | edit | page to edit user with id 1 |
PUT | /users/1 | update | update user with id 1 |
DELETE | /users/1 | destroy | delete user with id 1 |
7.调用控制台与数据库交互
$ rails console >> first_user = User.first => #<User id: 1, name: "Michael Hartl", email: "michael@example.org", created_at: "2011-11-03 02:01:31", updated_at: "2011-11-03 02:01:31"> >> first_user.microposts
>> exit
这里,如果需要重载,键入:reload!
退出命令: Ctrl-d 或者 exit
第三章
1.新建一个忽略rails默认测试框架的新项目(我们使用RSpec来进行测试)
$ rails new sample_app --skip-test-unit
source 'https://rubygems.org'
gem 'rails', '3.2.8'
gem 'bootstrap-sass', '2.0.4'
gem 'bcrypt-ruby', '3.0.1'
gem 'faker', '1.0.1'
gem 'will_paginate', '3.0.3'
gem 'bootstrap-will_paginate', '0.0.6'
gem 'jquery-rails', '2.0.2'
group :development, :test do
gem 'sqlite3', '1.3.5'
gem 'rspec-rails', '2.11.0'
# gem 'guard-rspec', '0.5.5'
# gem 'guard-spork', '0.3.2'
# gem 'spork', '0.9.0'
end
# Gems used only for assets and not required
# in production environments by default.
group :assets do
gem 'sass-rails', '3.2.5'
gem 'coffee-rails', '3.2.2'
gem 'uglifier', '1.2.3'
end
group :test do
gem 'capybara', '1.1.2'
gem 'factory_girl_rails', '1.4.0'
gem 'cucumber-rails', '1.2.1', :require => false
gem 'database_cleaner', '0.7.0'
# gem 'launchy', '2.1.0'
# gem 'rb-fsevent', '0.9.1', :require => false
# gem 'growl', '1.0.3'
end
group :production do
gem 'pg', '0.12.2'
end
其中,pg是为了部署在heroku上面。
$ bundle install --without production
注意这里有一个细节,bundle install 后面的--without porduction是一个能够被记住的命令,以后bundle的时候,不用再敲这个可选命令,默认不再安装生产环境。
3.接着,我们配置Rails,让RSpec取代test:unit成为我们的测试工具
$ rails generate rspec:install
4.到这里,我们算是完成了项目的初始化,现在加入git
$ git init
$ git add .
$ git commit -m "Initial commit"
5.为了使readme这个文件更有帮助,而不是一大堆rails初始化之后的文字,我们将其变为markdown语言
# Ruby on Rails Tutorial: sample application
This is the sample application for
[*Ruby on Rails Tutorial: Learn Rails by Example*](http://railstutorial.org/)
by [Michael Hartl](http://michaelhartl.com/).
文件名称更改
$ git mv README.rdoc README.md
$ git commit -a -m "Improve the README"
6.现在在github上新建项目,然后提交git库代码上去。
7.顺便部署在heroku上呗
$ heroku create --stack cedar
$ git push heroku master
8.开始为项目加入静态页面
先确保我们安装了rspec,用来进行测试
$ rails generate rspec:install
然后,通过以下来创建一个控制器
$ rails generate controller StaticPages home help --no-test-framework
$ rails generate controller FooBars baz quux $ rails destroy controller FooBars baz quux
$ rails generate model Foo bar:string baz:integer
$ rails destroy model Foo
第四章
1.
('a'..'z').to_a.shuffle[0..7].join
Let’s build it up step-by-step:
>> ('a'..'z').to_a # An alphabet array
=> ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o",
"p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
>> ('a'..'z').to_a.shuffle # Shuffle it.
=> ["c", "g", "l", "k", "h", "z", "s", "i", "n", "d", "y", "u", "t", "j", "q",
"b", "r", "o", "f", "e", "w", "v", "m", "a", "x", "p"]
>> ('a'..'z').to_a.shuffle[0..7] # Pull out the first eight elements.
=> ["f", "w", "i", "a", "h", "p", "c", "x"]
>> ('a'..'z').to_a.shuffle[0..7].join # Join them together to make one string.
=> "mznpybuj"
2.新旧hash符号对比
>> h1 = { :name => "Michael Hartl", :email => "michael@example.com" }
=> {:name=>"Michael Hartl", :email=>"michael@example.com"}
>> h2 = { name: "Michael Hartl", email: "michael@example.com" }
=> {:name=>"Michael Hartl", :email=>"michael@example.com"}
>> h1 == h2
=> true
3.hash也响应each方法
>> flash = { success: "It worked!", error: "It failed." } => {:success=>"It worked!", :error=>"It failed."} >> flash.each do |key, value| ?> puts "Key #{key.inspect} has value #{value.inspect}" >> end Key :success has value "It worked!" Key :error has value "It failed."
4.当hash作为参数的最后一个传递的时候,中括号是可以省略的
When hashes are the last argument in a function call, the curly braces are optional; these two lines are equivalent:
# Curly braces on final hash arguments are optional.
stylesheet_link_tag "application", { :media => "all" }
stylesheet_link_tag "application", :media => "all"
第五章
1. 用 match '/help' , to:'static_pages#help',替换掉get "static_pages/help"
前者是定义了一种路由,到help方法,这时候会自动生成在控制器和view里用到的命名路由:help_path或者help_url,这两种
uri helper定义如下
about_path => '/about'
about_url => 'http://localhost:3000/about'
第六章
1. rails c --sandbox
2.(做这里的时候出错,删除了本地文件,clone了github上的文件,遇到几个问题):
一。 git clone到本地之后,运行bundle install提示我pg这个gem安装不成功,后来才发现,这是为生产环境所添加的gem,需要bundle install --without product这样的命令,一切都OK。
二。手动删除了本地public/index.html文件之后,发现提交时候一直出现delete项的提示,在github上看远程文件也还在,并没有更新远程代码。后来才发现,不能直接本地手动删除,需要git rm public/index.html这样删除,才能够提交到远程。
3.沙盒中练习对数据表的一些操作
$ rails console --sandbox
Loading development environment in sandbox
Any modifications you make will be rolled back on exit
>>
>> User.new
=> #<User id: nil, name: nil, email: nil, created_at: nil, updated_at: nil>
>> user = User.new(name: "Michael Hartl", email: "mhartl@example.com") => #<User id: nil, name: "Michael Hartl", email: "mhartl@example.com", created_at: nil, updated_at: nil>
>> user.save => true
>> user
=> #<User id: 1, name: "Michael Hartl", email: "mhartl@example.com",
created_at: "2011-12-05 00:57:46", updated_at: "2011-12-05 00:57:46">
>> user.name => "Michael Hartl" >> user.email => "mhartl@example.com" >> user.updated_at => Tue, 05 Dec 2011 00:57:46 UTC +00:00
>> User.create(name: "A Nother", email: "another@example.org") #<User id: 2, name: "A Nother", email: "another@example.org", created_at: "2011-12-05 01:05:24", updated_at: "2011-12-05 01:05:24"> >> foo = User.create(name: "Foo", email: "foo@bar.com") #<User id: 3, name: "Foo", email: "foo@bar.com", created_at: "2011-12-05 01:05:42", updated_at: "2011-12-05 01:05:42">
>> foo.destroy => #<User id: 3, name: "Foo", email: "foo@bar.com", created_at: "2011-12-05 01:05:42", updated_at: "2011-12-05 01:05:42">
>> foo => #<User id: 3, name: "Foo", email: "foo@bar.com", created_at: "2011-12-05 01:05:42", updated_at: "2011-12-05 01:05:42">
>> User.find(1)
=> #<User id: 1, name: "Michael Hartl", email: "mhartl@example.com",
created_at: "2011-12-05 00:57:46", updated_at: "2011-12-05 00:57:46">
>> User.find(3)
ActiveRecord::RecordNotFound: Couldn't find User with ID=3
>> User.find_by_email("mhartl@example.com")
=> #<User id: 1, name: "Michael Hartl", email: "mhartl@example.com",
created_at: "2011-12-05 00:57:46", updated_at: "2011-12-05 00:57:46">
>> User.first => #<User id: 1, name: "Michael Hartl", email: "mhartl@example.com", created_at: "2011-12-05 00:57:46", updated_at: "2011-12-05 00:57:46"
一些更新练习
>> user # Just a reminder about our user's attributes
=> #<User id: 1, name: "Michael Hartl", email: "mhartl@example.com",
created_at: "2011-12-05 00:57:46", updated_at: "2011-12-05 00:57:46">
>> user.email = "mhartl@example.net"
=> "mhartl@example.net"
>> user.save
=> true
>> user.email
=> "mhartl@example.net"
>> user.email = "foo@bar.com"
=> "foo@bar.com"
>> user.reload.email
=> "mhartl@example.net"
>> user.created_at
=> "2011-12-05 00:57:46"
>> user.updated_at
=> "2011-12-05 01:37:32"
6.2数据验证
验证存在
class User < ActiveRecord::Base
attr_accessible :name, :email
validates :name, presence: true
end
可以通过控制台的沙盒查看
$ rails console --sandbox
>> user = User.new(name: "", email: "mhartl@example.com")
>> user.save
=> false
>> user.valid?
=> false
这里,我们还有一个函数,可以查看完整的出错信息
>> user.errors.full_messages => ["Name can't be blank"]
验证长度
class User < ActiveRecord::Base
attr_accessible :name, :email
validates :name, presence: true, length: { maximum: 50 }
validates :email, presence: true
end
验证邮箱
class User < ActiveRecord::Base
attr_accessible :name, :email
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }
end
练习正则表达式:
常用的正则表达式
Expression | Meaning |
---|---|
/\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i | full regex |
/ | start of regex |
\A | match start of a string |
[\w+\-.]+ | at least one word character, plus, hyphen, or dot |
@ | literal “at sign” |
[a-z\d\-.]+ | at least one letter, digit, hyphen, or dot |
\. | literal dot |
[a-z]+ | at least one letter |
\z | match end of a string |
/ | end of regex |
i | case insensitive |
验证邮箱,并且是大小写不敏感的
class User < ActiveRecord::Base
.
.
.
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
end
但是,通过这样的验证,就能证明我们用户的邮箱保证不重叠么?不是这样的,设想,如果John提交了两次,这两次在极其短暂的时间,那么就会通过这两次验证,数据库中就会存在两个一样的email。在大量访问的情况下,这种情况就更普遍了,所以,为了避免这种情况,我们需要在数据库层级的email列创建一个索引,然后要求索引是惟一的。
这时候,我们需要添加一个索引
$ rails generate migration add_index_to_users_email
与产生users的时候不同,我们需要手动添加内容
class AddIndexToUsersEmail < ActiveRecord::Migration
def change
add_index :users, :email, unique: true
end
end
然后数据迁移
bundle exec rake db:migrate
update-to Listing 6.22.
问题,数据库迁移没成功,以前遇到过这种问题,明晚重新启动再看看。
果然,重启之后,成功迁移。。。
6.3 Adding a secure password