The default library for interacting with the database is called Active Record. Active Record comes with a host of methods for creating, saving, and finding data objects, all without having to use the structured query language (SQL)2 used by relational databases. Active Record有保存创造查询数据的方法,这些方法没必要使用SQL来操作关系数据库。
Migration for the User model (to create a users table). db/migrate/[timestamp]_create_users.rb
class CreateUsers < ActiveRecord::Migration def change create_table :users do |t| t.string :name t.string :email t.timestamps end end endHere the table name is plural (users) even though the model name is singular (User), which reflects a linguistic convention followed by Rails: a model represents a single user, whereas a database table consists of many users. //建了一个Users类,是单数的,它的数据库是复数的。
created_at和updated_at是自动生成的。
bundle exec rake db:migrate 和 bundle exec rake db:rollback 是相反的两个语句。
gem 'annotate', '2.5.0', group: :developmentThis gives us a command called annotate, which simply adds comments containing the data model to the model file:
$ bundle exec annotate
Annotated (1): User 这是用来添加注释的
结果如下:
# == Schema Information # # Table name: users # # id :integer not null, primary key # name :string(255) # email :string(255) # created_at :datetime # updated_at :datetime # class User < ActiveRecord::Base attr_accessible :name, :email end
$ rails console --sandbox We don’t (yet) want to make any changes to our database, we’ll start the console in a sandbox:
p=User.new("xxx","xxx@xxx") 如果用p.save就可以保存created_at和updated_at时间了,并且存入数据库。
p.destroy取消p.save
User.find(1);基于id来寻找用户
User.find_by_email("[email protected]") 这个是自动生成的
The find_by_email
method is automatically created by Active Record based on the email
attribute in the users
table. (As you might guess, Active Record creates a find_by_name
method as well.)
还有 User.first, User.all
user.update_attributes(name: "The Dude", email: "[email protected]")这儿是用来更新文档数据库。
让rails 持续工作:rails s -d,关掉持续工作:杀掉某个进程 一般的用法是kill -9 pid,关闭rails方法:lsof -i:3000后,找到pid,然后kill
class User < ActiveRecord::Base attr_accessible :name, :email validates :name, presence: true
before_save { |user| user.email = email.downcase } end
如果添加了名字为空的记录,p.save结果为false,那么p.error.full_messages可以看出错在哪
在User的model中用来限制email字段的格式:
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }
正则表达式工具网站:http://www.rubular.com/
如果要求字段是唯一的,比如邮箱只能有一个
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }(不忽略大小写)
但是光光这样不能满足要求,在互联网交通中。所以我们必须将目光深入到数据库层,修改数据库,建立唯一列属性。
rails generate migration add_index_to_users_email这一条是建立数据迁移名称,修改改迁移表为如下,增加
class AddIndexToUsersEmail < ActiveRecord::Migration def change add_index :users, :email, unique: true end endbundle exec rake db:migrate 数据迁移,设定好
用来加密的第三方gem,在Gemfile中添加
gem 'bcrypt-ruby', '3.0.1'
bundle install
rails generate migration add_password_digest_to_users password_digest:string 更新数据库
bundle exec rake db:migrate
通过一些其他的元素来寻找,而不是普通的id: user = User.find_by_email(email)
current_user = user.authenticate(password) 这个代码是用来验证password的,如果验证错误返回false
密码操作函数:has_secure_password
As long as there is a password_digest column in the database, adding this one method to our model gives us a secure way to create and authenticate new users.首先要新建以下两个属性,并且设置:
validates :password, presence: true, length: { minimum: 6 }
validates :password_confirmation, presence: true 其中一个是密码,一个再次确定密码,在has_secure_password中已经自动生成了这两个属性,并且如此命名,如果你在创建记录时,这两个值不一样,则创建不成功
最后,在真正用户验证的时候用命令:
user = User.find_by_email("[email protected]")
user.authenticate("invalid")