专栏首页技术沉淀Rails里应用Devise

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.

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

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 条评论
登录 后参与评论

相关文章

  • Rails应用分页: Will Paginate

    用户2183996
  • Rails里应用Markdown

    用户2183996
  • Python: 遍历字典

    用户2183996
  • 腾讯产品经理现身说法:to b的产品经理和to c产品经理区别

    用户1756920
  • 个性化语法纠错:根据能力水平和 L1 进行调整(CS CL)

    语法纠错 (GEC) 系统在各种软件应用中已变得无处不在,并已开始在某些数据集上接近人类水平的性能。然而,对于如何根据用户的特点(如用户的熟练程度和第一语言)或...

    刘持诚
  • C++核心准则C.152:永远不要将派生类数组的指针赋值给基类指针

    Subscripting the resulting base pointer will lead to invalid object access and p...

    面向对象思考
  • Elixir, OTP, Ecto, 和 Phoenix 免费教程!

    时见疏星
  • 通过共分割实现基于涂鸦的域自适应

    中文摘要:虽然深卷积网络在许多医学图像分割任务中已经达到了最先进的性能,但它们通常表现出较差的泛化能力。为了能够从一个领域(例如,一种成像模式)归纳到另一个领域...

    用户7454122
  • Python学习教程(二)

    输入输出 交互式输入输出 在很多时候,你会想要让你的程序与用户(可能是你自己)交互。你会从用户那里得到输入,然后打印一些结果。我们可以分别使用raw_input...

    生信宝典
  • 患者的个人健康知识图(CS.AI)

    现有的患者数据分析平台无法整合具有上下文,个性化和主题性的信息。为了使推荐系统对查询做出适当的响应或从患者数据中得出有意义的见解,推荐系统应考虑有关患者健康史的...

    蔡小雪7100294

扫码关注云+社区

领取腾讯云代金券