Rails里应用Devise

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.

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.

<% 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.

<% if user_signed_in? %>
    <%= link_to "Sign Out", destroy_user_session_path, method: :delete %>
<% end %>

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏python开发教学

rest_framework框架的基本组件

1002
来自专栏iOSDevLog

Learn Android Studio 3Android architectureAndroid ComponentsDesign editor.pngKeyboard Shortcuts for

2888
来自专栏技术博文

php QR Code二维码生成类

<?php /* * PHP QR Code encoder * * This file contains MERGED version of PHP ...

3645
来自专栏Netkiller

怎样制作RPM包

怎样制作RPM包 摘要 我在网上找RPM包的制作例子几乎都是C源码编译安装然后生成RPM包, 而我的程序不是C写的很多时候是脚本语言如Python, PHP 甚...

5516
来自专栏三杯水

Ambari安装部署Hadoop

Apache Ambari是一种基于Web的工具,支持Apache Hadoop集群的供应、管理和监控。Ambari已支持大多数Hadoop组件,包括HDFS、...

2073
来自专栏bboysoul

linux编译安装apache

wget http://mirrors.ustc.edu.cn/apache/httpd/httpd-2.4.25.tar.gz tar -zxvf http...

1563
来自专栏后台及大数据开发

CentOS下redis集群安装

环境: 一台CentOS虚拟机上部署六个节点,创建3个master,3个slave节点

782
来自专栏杨建荣的学习笔记

PCIE的简单配置(r8笔记第82天)

最近测试了一下PCIE-SSD在数据库环境的迁移 和加压情况,IOPS无可置疑,比起机械硬盘确实是高了很多个量级,在数据环境中的IO方面确实有很稳定的提升,目...

3538
来自专栏Golang语言社区

也许你并不需要 REST

Nearly 10 years ago, Leonard Richardson and Sam Ruby publishedRESTful Web Servic...

702
来自专栏技术沉淀

Rails应用分页: Will Paginate

1023

扫码关注云+社区