Rails Tutorial學(xué)習(xí)筆記

1.helpers幫助函數(shù)如果需要控制器和視圖中同時使用的話,可以使用下面方法

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  include SessionsHelper#引用幫助函數(shù)
end

2.用戶賬號密碼相關(guān)
①數(shù)據(jù)庫指定字段唯一性
rails generate migration add_index_to_users_email
db/migrate/[timestamp]_add_index_to_users_email.rb

class AddIndexToUsersEmail < ActiveRecord::Migration
  def change
    add_index :users, :email, unique: true
  end
end

②加上安全密碼
使用目前最先進(jìn)的哈希函數(shù) bcrypt 對密碼進(jìn)行不可逆的加密,得到密碼的哈希值
在gemfile文件中加入
gem 'bcrypt-ruby', '3.1.7'
給用戶表添加密碼字段
rails generate migration add_password_digest_to_users password_digest:string
在用戶模型添加中添加has_secure_password方法之后,會自動生成password 和 password_confirmation 屬性,二者都要填寫一些內(nèi)容(非空格),而且要相等;還要定義 authenticate 方法,對比加密后的密碼和 password_digest 是否一致,驗(yàn)證用戶的身份。這對于用戶驗(yàn)證是非常方便的。
下面是一個用戶模型的示例。

class User < ActiveRecord::Base
  before_save { self.email = email.downcase }
  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 },
                    uniqueness: { case_sensitive: false }
  has_secure_password
  validates :password, length: { minimum: 6 }
end

到這里就可以使用rails命令行來添加用戶了

$ rails console
>> User.create(name: "Michael Hartl", email: "mhartl@example.com",
?>             password: "foobar", password_confirmation: "foobar")
=> #<User id: 1, name: "Michael Hartl", email: "mhartl@example.com", created_at: "2013-03-11 20:45:19", updated_at: "2013-03-11 20:45:19", password_digest: "$2a$10$kn4cQDJTzV76ZgDxOWk6Je9A0Ttn5sKNaGTEmT0jU7.n...">

3.用戶登錄相關(guān)
①通過session來管理登錄
在路由文件中添加session資源
resources :sessions, only:[:new,:create,:destroy]
表單登錄文件

<% provide(:title, "Sign in") %>
<h1>Sign in</h1>

<div class="row">
  <div class="span6 offset3">
    <%= form_for(:session, url: sessions_path) do |f| %>

      <%= f.label :email %>
      <%= f.text_field :email %>

      <%= f.label :password %>
      <%= f.password_field :password %>

      <%= f.submit "Sign in", class: "btn btn-large btn-primary" %>
    <% end %>

    <p>New user? <%= link_to "Sign up now!", signup_path %></p>
  </div>
</div>

表單post提交控制器 session的create方法

def create
  user = User.find_by(email: params[:session][:email].downcase)
  if user && user.authenticate(params[:session][:password])
    sign_in user#用戶登錄成功就使用該方法記住該用戶
  else
    # Create an error message and re-render the signin form.
  end
end

由于我們需要長期記錄用戶登錄狀態(tài),最安全的做法就是為每個用戶生成一個安全標(biāo)示符。具體的實(shí)現(xiàn)方法如下:
為用戶表添加一個remember_token字段,該字段記錄用戶的登錄情況。
rails g migration add_remember_token_to_users remember_token:string
因?yàn)槲覀兘?jīng)常需要根據(jù)字段提取用戶信息,所以我們也需要為該字段建立數(shù)據(jù)庫索引

class AddRememberTokenToUsers < ActiveRecord::Migration
  def change
    add_column :users, :remember_token, :string
    add_index :users, :remember_token
  end
end

實(shí)現(xiàn)過程。首先我們先使用Ruby 標(biāo)準(zhǔn)庫中 SecureRandom 模塊提供的 urlsafe_base64方法生成一個長度為16的隨即字符串,然后使用 SHA1 加密了記憶權(quán)標(biāo)保存到數(shù)據(jù)庫,用戶登錄時,查詢用的remember_token是否和數(shù)據(jù)庫中的一致,如果一致則判斷為登錄用戶。

在User模型中添加創(chuàng)建remember_token的方法,在注冊用戶時,自動為每個用戶添加一個remember_token。

class User < ActiveRecord::Base
  before_save { self.email = email.downcase }
  before_create :create_remember_token
  .
  .
  .
  def User.new_remember_token
    SecureRandom.urlsafe_base64
  end

  def User.hash(token)
    Digest::SHA1.hexdigest(token.to_s)
  end

  private

    def create_remember_token
      self.remember_token = User.hash(User.new_remember_token)
    end
end

再來看看我們的登錄方法:

module SessionsHelper

  def sign_in(user)
    remember_token = User.new_remember_token
    cookies.permanent[:remember_token] = remember_token
    user.update_attribute(:remember_token, User.hash(remember_token))#更新單個屬性并保存到數(shù)據(jù)庫
    self.current_user= user#該方法是
  end
end

其中permanent方法時下面的簡寫模式

cookies[:remember_token] = { value:   remember_token,
                         expires: 20.years.from_now.utc }

我們來看看current_user= 方法的定義

def current_user=(user)
    @current_user = user
end

如果我們想要獲取當(dāng)前登錄的用戶,可以使用下面的方法

def current_user
    remember_token = User.hash(cookies[:remember_token])
    @current_user ||= User.find_by(remember_token: remember_token)
end

當(dāng)然我們需要定義一個常用的方法來判斷用戶是否登錄

def signed_in?
    !current_user.nil?#如果方法current_user為空,current_user.nil?為真,則signed_in?返回假,即用戶沒有登錄
end

②退出登錄
方法如下
在session控制器中添加下面的方法

def destroy
    sign_out
    redirect_to root_path
end

在session幫助中添加下面的方法

def sign_out
    #改變當(dāng)前登錄用戶的remember_token字段的值
    current_user.update_attribute(:remember_token,
                                  User.hash(User.new_remember_token))
    self.current_user = nil
    cookies.delete(:remember_token)
end

4.rails分頁
首先在gemfile文件中添加下面
gem 'will_paginate', '3.0.4'添加分頁插件
在控制器中:

def index
    @users = User.paginate(page: params[:page], pre_page: 10)#每頁顯示10條記錄
end

在視圖中

  <%= will_paginate %>

就可以直接實(shí)現(xiàn)分頁效果了,很簡單吧。。。

5.精簡視圖文件

<ul class="users">      
    <%= render @users %>      
</ul>

這里的@users不是指定視圖文件,而是使用哪個了@users變量。Rails 會自動去尋找一個名為 _user.html.erb 的局部視圖,我們要手動創(chuàng)建這個視圖,然后寫入代碼

<li>
  <%= gravatar_for user, size: 52 %>
  <%= link_to user.name, user %>
</li>

Rails 會把 @users 當(dāng)作一系列的 User 對象,遍歷這些對象,然后使用 _user.html.erb 渲染每個對象。所以我們就得到了非常簡潔的代碼。

6.添加管理員用戶
我們?yōu)槊總€添加一個字段admin,該字段為bool類型,每個用戶實(shí)例都會存在一個admin?方法,所以我們可以使用該方法來判斷是否為管理員,實(shí)現(xiàn)方法如下:
首先,我們需要為users表單添加admin字段
rails generate migration add_admin_to_users admin:boolean
當(dāng)然我們也需要為該字段設(shè)定一個默認(rèn)值

class AddAdminToUsers < ActiveRecord::Migration
  def change
    add_column :users, :admin, :boolean, default: false
  end
end
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,554評論 19 139
  • 22年12月更新:個人網(wǎng)站關(guān)停,如果仍舊對舊教程有興趣參考 Github 的markdown內(nèi)容[https://...
    tangyefei閱讀 35,399評論 22 257
  • 背景: 最近比較閑,想學(xué)習(xí)ruby on rails 于是找到了https://www.railstutorial...
    pingpong_龘閱讀 1,071評論 0 3
  • 此段內(nèi)容簡要來自自強(qiáng)學(xué)堂的教程詳情請查詢自強(qiáng)學(xué)堂 一、 后臺的運(yùn)作流程 接收request請求 處理數(shù)據(jù) 獲取請求...
    coder_ben閱讀 5,345評論 6 56
  • 最近過得怎么樣。 工作還順心嗎?業(yè)績怎么樣,壓力還是那么大嗎?我不在的日子里,你又有像誰吐槽工作中的各種事情呢?還...
    養(yǎng)兔子的姑娘閱讀 333評論 0 0

友情鏈接更多精彩內(nèi)容