使用devise这个gem只需要简单几步就能做好用户注册登录等功能,能节省大量时间和精力。
1.安装devise
1 2 3 4 5 6 7 8 9 10 11 12
   |  gem 'devise'
  bundle install
  rails g devise:install
  rails g devise user
  rails g devise:views
  rake db:migrate
 
  | 
 
2.使用
1 2 3 4 5
   |  rails g controller home index --no-helper --no-assets
  root 'home#index'
 
 
  | 
 
1 2 3 4 5 6 7 8
   | <h1>Home#index</h1> <% if user_signed_in? %>   hello, <%= current_user.username %><br />   <%= link_to('登出', destroy_user_session_path, :method => :delete) %> <% else %>   <%= link_to('注册', new_registration_path(:user)) %>   <%= link_to('登录', new_session_path(:user)) %> <% end %>
   | 
 
此时访问http://localhost:3000就可以使用注册登录功能了。
另附两个有用到的链接:
1.添加用户名登录 How To: Allow users to sign in using their username or email address
2.添加管理员角色 How To: Add an Admin Role