4-5 14章

今日学习:

上午: 

  • Logging In 基础原码学习,加练习题。加部分资料扩展。(9:15开始)
下午:
  • Logging in,看ActiveRecord Transactions,http://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html#method-i-transaction
晚上:
  • 做明天计划:
  • international: i18n国际化翻译页面,加练习。
  • 部署练习。根据实际情况。
  • guide都看一下,熟悉的看英文原版,不熟悉的看中文
  • 5.1,5.0的一些新特点的实际练习
  • javascript的基础学习。 

 本章所学: 

1.使用ActiveModel::SecurePassword.对密码储存为指纹hash值。

 3个实例方法,一个类方法。

 authenticate("未加密的密码") => true/false

 password=("未加密的密码") => "未加密的密码" 

 password_confirmation=(unencrypted_password) 
class User < ActiveRecord::Base
  has_secure_password validations: false #类方法
end

user = User.new
user.password = nil
user.password_digest # => nil
user.password = 'mUc3m00RsqyRe'
user.password_digest # =>输出加密的密码 "$2a$10$4LEA7r4YmNHtvlAvHhsYAeZmk/xeUVtMTYqwIvYY76EW5GUqDiP4."

rails g User name password:digest,自动include近ActiveRecord中了。

在create_table块中,t.string :password_digest

迁移后,在User.rb中,添加上面模块的has_secure_password方法。

需要加gem bcrypt.  

2.练习controller的测试

3.在application.rb设置前置回调before_action :authorize方法,并使用skip_before_action :authorzie, only:[...,...]

4.学习transaction事物 

Transactions are protective blocks where SQL statements are only permanent if they call all succeed as one atomic action.

事物是受到保护的块。什么块 ?只有当SQL代码块作为一个整体动作被全部成功调用的时候,才会是永久的(储存在数据库中 ),否则就不会执行这个代码块。

save and destroy are automatically wrapped in a transaction.可以使用validations or callback。 

Exception信息处理和rolling back

ActiveRecord::Rollback只会终止事务,但不会抛出异常信号。

事务可以嵌套

Callbacks:

  • after_commit:成功后的钩子操作,比如清理a cache
  • after_rollback: 失败后的钩子操作

 

ActiveModel::Errors

Provides a modified Hash that you can include in your object for handling error messages and interacting with Action View helpers.

 有20多个方法。如full_message, each, empty?, add, delete

例子:

add(attribute, message = :invalid, options = {})

  @user.errors.add(:current_password, "for user is incorrect") 

=> Current password for user is incorrect


练习题:

1. 修改更新用户的功能,要求在更改密码之前先输入并验证当前密码。

  第一步,在_form.html.erb的form表中插入,判断的语句,因为这个是通用partial

      <% if params[:action] == 'edit' || params[:action] == 'update' %>
        <div class="field">
          <%= form.label :current_password, '当前密码:' %>
          <%= form.password_field :current_password, size: 40,          id:user_password%>
        </div>
      <% end %>

  第二步,在update方法内添加判断和验证以及错误提示。

  def update
    # cp = params[:user].delete(:current_password),无需删除,因为有user_params方法验证

    #传入参数是params是类hash值。 

    cp = params[:user][:current_password]
    respond_to do |format|
      if @user.authenticate(cp)
        if @user.update(user_params)
          format.html { redirect_to users_url,
            notice: "User #{@user.name} was successfully updated." }
          format.json { render :show, status: :ok, location: @user }
        else
          format.html { render :edit }
          format.json { render json: @user.errors, status: :unprocessable_entity }
        end
      else
        @user.errors.add(:current_password, "for user is incorrect")
        format.html { render :edit }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end
原文地址:https://www.cnblogs.com/chentianwei/p/8721220.html