您的位置:首页 > 编程语言 > Ruby

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

2016-01-01 18:50 816 查看
本文使用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>


完成!

运行效果:







内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ruby rails devise