1.home page
$rails generate controller StaticPages home help
2. test
rails test
3. add CSS
gem bootstrap-sass in gemfile
或者直接在assert static.scss改
$ touch app/assets/stylesheets/custom.scss
导入 Bootstrap 中的 CSS app/assets/stylesheets/custom.scss
@import "bootstrap-sprockets";
@import "bootstrap";
4.在layouts中加header,foot
5.add path in routes
get '/contact', to: 'static_pages#contact'
这样就可以直接用 <%= link_to "Contact", contact_path %>
6.login page controller-model -view
rails generate controller Users new
rails generate model User name:string email:string
rails db:migrate
在sandbox中增加user
rails console --sandbox
user = User.new(name: "Mi", email: "mtl@example.com")
user.save
User.find(1)
User.find_by(email:"mtl@example.com")
>> user.email => "mhartl@example.net" >> user.email = "foo@bar.com" => "foo@bar.com" >> user.reload.email => "mhartl@example.net"
app/models/user.rb
class User < ApplicationRecord
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /A[w+-.]+@[a-zd-]+(.[a-zd-]+)*.[a-z]+z/i
validates :email,presence: true,length:{maximum:255},
format: { with: VALID_EMAIL_REGEX }
uniqueness: { case_sensitive: false }
end
为 email 列建立索引要改变数据模型,实现电子邮件地址唯一性
rails generate migration add_index_to_users_email
IN db/migrate/[timestamp]_add_index_to_users_email.rb
class AddIndexToUsersEmail < ActiveRecord::Migration[5.0]
def change
add_index :users, :email, unique: true
end
end
$rails db:migrate
我们使用的安全密码机制基本上用一个 Rails 方法即可实现,这个方法是 has_secure_password。我们要在
User MODEL中调用这个方法,如下所示:
class User < ApplicationRecord .
has_secure_password
end
$ rails generate migration add_password_digest_to_users password_digest:string
$rails db:migrate
试试错误密码~~
>> user.authenticate("not_the_right_password") false >> user.authenticate("foobaz") false
----------------user model finished ---------------
---------------- login ---------------
显示用户的信息
def show
@user = User.find(params[:id])
end
前面创建了一个略显简陋的用户资料页面,这一节要再添加一些内容:用户头像和侧边栏。首先,我们要在 用户资料页面添加一个全球通用识别头像,或者叫 Gravatar。7 这是一个免费服务,让用户上传图像,将其关 联到自己的电子邮件地址上。使用 Gravatar 可以简化在网站中添加用户头像的过程,开发者不必分心去处理 图像上传、剪裁和存储,只要使用用户的电子邮件地址构成头像的 URL 地址,用户的头像就能显示出来
app/views/users/show.html.erb
<% provide(:title, @user.name) %> <h1>
<%= gravatar_for @user %>
<%= @user.name %> </h1>
app/helpers/users_helper.rb
module UsersHelper # 返回指定用户的 Gravatar def gravatar_for(user) gravatar_id = Digest::MD5::hexdigest(user.email.downcase) gravatar_url = "https://secure.gravatar.com/avatar/#{gravatar_id}" image_tag(gravatar_url, alt: user.name, class: "gravatar") end end