前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Rails里应用Devise

Rails里应用Devise

作者头像
用户2183996
发布2018-06-28 10:48:44
3140
发布2018-06-28 10:48:44
举报
文章被收录于专栏:技术沉淀技术沉淀

Use Devise For Authentication

Devise is great gem for authentication, check out here.

Add Gem

First thing you need to do is to add devise gem to you Gemfile. Just add gem 'devise', '~> 3.5' to your Gemfile and run bundle install and restart your server.

Set Up

Run generator rails generate devise:install to install an initializer. Devise will generate lots of file, git status to checkout. Also there will be some guides for what to do next in the terminal, just do as indicated! Something like make sure there is homepage, rails g devise:views and configuration stuff.

Generate User

Say you want to generate a user model. Just run rails g devise User and rake db:migrate. Then you can go to users/sign_up to create a new account.

Devise It

Authenticate Users

Now you can authenticate users! Say you want that only users that have signed in can edit or delete posts, otherwise, they can only go for index and show pages. It's pretty easy, just add this code to your posts_controller.rb file.

代码语言:javascript
复制
before_action: authenticate_user!, except: [:index, :show]

Then unauthenticated users will be redirected to sign up page if they want to edit or delete posts.

Show Edit and Delete Link for Users Signed In

If you want the Edit and Delete button shown for users signed in. Add this code to your view.

代码语言:javascript
复制
<% if user_signed_in? %>
    <div id="admin_links">
        <%= link_to "Edit Article", edit_post_path(@post) %>
        <%= link_to "Delete Article", post_path(@post), method: :delete, data: {confirm: "Are you sure?"} %>
    </div>
<% end %>
Show Sign Out Link for Users Singed In

You may also want add a sign out link for users who have signed in. To do this, add this code to your _header.html.erb partial.

代码语言:javascript
复制
<% if user_signed_in? %>
    <%= link_to "Sign Out", destroy_user_session_path, method: :delete %>
<% end %>
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016.06.30 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Use Devise For Authentication
    • Add Gem
      • Set Up
        • Generate User
          • Devise It
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档