ruby on rails 注册登录模块的简单实现

本文使用Devise组件生成一个带有登录、注册等基本功能的认证模块。

Ruby版本为 2.2.1

Rails版本为 4.2.3


使用前可以先修改gem sources


言归正传~

1. 新建一个项目,使用mysql数据库

rails new demoDevise -d=mysql

2.修改 Gemfile文件,注意由于rails4自身原因,这里mysql2要进行版本设置,否则一直提示mysql2需要安装。如图所示:


bundle install

3. 

rails g devise:install
4. 修改 
config/environments/development.rb 或者production.rb,上边加入:

config.action_mailer.default_url_options = { :host => 'localhost:3000' }

5. 修改 routes.rb

devise_for :users
root :to => "welcome#index"

6. 

rails g devise user 
rake db:migrate

7. 
rails g devise:views

8. devise默认使用email字段登录,添加username取代email

rails g migration add_username_to_users
 加入代码

add_column :users, :username, :string

确认修改

rake db:migrate

9. 修改 ApplicationController

class ApplicationController < ActionController::Base                        
  before_action :configure_permitted_parameters, if: :devise_controller?
  protect_from_forgery with: :exception
  protected
 
  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up)  { |u| u.permit(:email, :userna    me, :password, :password_confirmation) }
    devise_parameter_sanitizer.for(:account_update) << :username
  end
end

10. 修改  views/devise/registrations/edit.html.erb 和 new.html.erb,加上:

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

11. 在 views/layouts  新建_user_widget.html.erb
 <% if user_signed_in? %>                                                    
   <p>Welcome <%= current_user.username %></p>
   <%= link_to '退出', destroy_user_session_path, :method => :delete %>
   <%= link_to '回到首页', root_path %>
 <% else %>
   <p>You are not signed in.</p>
   <%= link_to 'Login', new_user_session_path %>
 <% end %>

12.  views/layouts/application.html.erb  加入

<body>
  <p class="notice"><%= notice %></p>
  <p class="alert"><%= alert %></p>
  <%= yield %>
  <%= render 'layouts/user_widget' %>
</body>

13.  config/initializers/devise.rb  修改
config.authentication_keys = [:username]


14. 修改  app/views/devise/sessions/new.html.erb

<div class="field">
  <%= f.label :username %><br />
  <%= f.text_field :username, autofocus: true %>
</div>

<div class="field">
  <%= f.label :password %><br />
  <%= f.password_field :password, autocomplete: "off" %>
</div>

完成!

运行效果:





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值