Devise使用指南

作者: youngiyang_打码少年 | 来源:发表于2016-09-08 13:38 被阅读3120次

    基本使用
    在Gemfile里面添加gem 'devise'
    运行bundle install
    然后安装devise相关组件,rails generate devise:install
    安装完提示如下,按照如下设置:

    Some setup you must do manually if you haven't yet:
    
      1. Ensure you have defined default url options in your environments files. Here
         is an example of default_url_options appropriate for a development environment
         in config/environments/development.rb:
    
           config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
    
         In production, :host should be set to the actual host of your application.
    
      2. Ensure you have defined root_url to *something* in your config/routes.rb.
         For example:
    
           root to: "home#index"
    
      3. Ensure you have flash messages in app/views/layouts/application.html.erb.
         For example:
    
           <p class="notice"><%= notice %></p>
           <p class="alert"><%= alert %></p>
    
      4. If you are deploying on Heroku with Rails 3.2 only, you may want to set:
    
           config.assets.initialize_on_precompile = false
    
         On config/application.rb forcing your application to not access the DB
         or load models when precompiling your assets.
    
      5. You can copy Devise views (for customization) to your app by running:
    
           rails g devise:views
    
    ===============================================================================
    

    2.执行命令rails g devise:views,生成devise的视图文件
    3.生成需要用到devise的模型,rails g devise user,运行了这条命令之后,路由中会自动生成一个devise_for :users,
    rake db:migrate,执行迁移文件

    4.新建一个控制器,rails generate controller home index,用来设置root页面

    5.在控制器中,设置访问之前需要先登录

    class HomeController < ApplicationController
      before_action :authenticate_user!, :only => [:index, :new]
    

    6.devise会默认创建一个帮助方法:
    before_action :authenticate_user!
    user_signed_in? //判断用户是否登录
    current_user //获取当前登录用户
    user_session //可以访问对应的session

    7.登录之后,devise会有默认跳转到root,如果想自定义跳转,需要覆盖after_sign_in_path_for和after_sign_out_path_for来自定义跳转回调。

    8.devise除了用emails登录之外,自定义登录字段
    rails generate migration add_username_to_users username:string
    增加字段后,执行rake db:migrate

    9.增加了新字段之后,在config/initializers/devise.rb中配置登录验证的字段
    config.authentication_keys = [:username]
    config.case_insensitive_keys = [:username]
    config.strip_whitespace_keys = [:username]

    10.修改完字段后,对应的去修改views里面的视图,把登录页面的email字段改成username,在注册页面新加上username的input

    11.修改完之后,接下来需要重写一个方法,用来配置登录和注册所允许的参数,将此方法写在application_controller.rb中

    def configure_permitted_parametersod_name
        devise_parameter_sanitizer.permit(:sign_in) {|u|               u.permit(:email, :username)}
        devise_parameter_sanitizer.permit(:sign_up) {|u|
        u.permit(:email, :username, :password,                      :password_confirmation)}
    end
    

    在application_controller.rb还需要配置
    before_action :configure_permitted_parametersod_name, if: :devise_controller?
    如果没有配置这个,在注册的时候,会出现邮箱验证不通过的BUG

    13.为了使得用户名和邮箱都可以登录,需要在user模型里加入一个
    虚拟属性:
    attr_accessor :signin
    然后在/config/ initializers/devise.rb中修改验证参数
    config.authentication_keys = [ :signin ]

    14.修改了验证参数之后,需要去模型里面重写登录devise会使用到的方法,在user.rb里面重写self.find_for_database_authentication方法

    def self.find_for_database_authentication(warden_conditions)
        conditions = warden_conditions.dup
        if signin = conditions.delete(:signin)
          where(conditions.to_h).where(["lower(username) = :value OR lower(email) = :value", { :value => signin.downcase }]).first
        elsif conditions.has_key?(:username) || conditions.has_key?(:email)
          where(conditions.to_h).first
        end
    end
    

    15.在模型里定义完方法之后,需要将application_controller.rb中那个允许参数的方法重写

      def configure_permitted_parametersod_name
        devise_parameter_sanitizer.permit(:sign_in) {|u| u.permit(:signin, :password, :remember_me)}
        devise_parameter_sanitizer.permit(:sign_up) {|u|
        u.permit(:email, :username, :password, :password_confirmation)}
      end
    

    16.去登录视图中,将username的input改成signin的input,这样一来,用用户名和邮箱都可以实现登录功能

    17.编辑用户资料的时候,需要允许用户修改用户名,邮箱,和密码
    首先在编辑页面加入username的input,方便修改用户名

    <div>
        <%= f.label :username %><br />
        <%= f.text_field :username %>
    </div>
    

    18.接下来要做的事情是去修改devise的逻辑,新建一个注册控制器叫做registrations_controller
    rails generate controller registrations update

    19.生成控制器后,更改update方法,在控制器registrations_controller中将update方法定义如下:

      def update
        new_params = params.require(:user).permit(:email,
        :username, :current_password, :password,
        :password_confirmation)
        @user = User.find(current_user.id)
        if @user.update_with_password(new_params)
          set_flash_message :notice, :updated
          sign_in @user, :bypass => true
          redirect_to after_update_path_for(@user)
        else
          render "edit"
        end
      end
    

    在健壮参数中加入username等属性,然后用update_with_password
    方法更新参数(这个方法是devise定义的)

    20.在更改过控制器之后,需要更改路由,使得修改账户的时候,默认跳到我们新加的registrations_controller控制器中,路由修改方式如下:
    devise_for :users, :controllers => {:registrations =>
    "registrations"}

     未完待续
    

    相关文章

      网友评论

        本文标题:Devise使用指南

        本文链接:https://www.haomeiwen.com/subject/numsettx.html