我们已经完成了Category & Product页面内容的增删改查,再加入一个身份验证即可成为一个较完整的Rails App了。本文就来完成这个任务。

We now need to give users the ability to sign up for the app so that they can do things like purchase products or leave reviews.

To do this, we'll add a user authentication system to the app.看下图:

1. install a gem called Devise.

Earlier, we learned about bundler and how it sets up our gems. To add authentication, we'll install a gem called Devise.

We've gone ahead and added Devise for you in your Gemfile. Run bundle to install it in your app.

【Instructions】

1. In your terminal, run
bundle install to update all your gems. Press Enter.

这个命令看起来好像是依托于一个叫做GemFile的文件的:

source 'https://rubygems.org'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.1.1'
# Use sqlite3 as the database for Active Record
gem 'sqlite3', '1.3.9'
# Use SCSS for stylesheets
gem 'sass-rails', '4.0.3'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '1.3.0'
# Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '4.0.0'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby gem 'paperclip', '4.2.0' # Use jquery as the JavaScript library
gem 'jquery-rails', '3.1.2'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks', '2.4.0'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '2.2.2'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '0.4.0', group: :doc # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring', '1.1.3', group: :development # Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7' # Use unicorn as the app server
# gem 'unicorn' # Use Capistrano for deployment
# gem 'capistrano-rails', group: :development # Use debugger
# gem 'debugger', group: [:development, :test] gem 'rspec', '3.1'
gem 'rspec-rails', '3.1'
gem 'rspec-context-private', '0.0.1'
gem 'rspec-html-matchers', '0.6.1' gem 'devise', '3.4.0'

运行那个命令以后就进入第二步。

以下是运行的部分结果打印:

$ bundle install
Fetching gem metadata from https://rubygems.org/..........
Resolving dependencies...
Using rake 10.3.2
Using i18n 0.6.11
....

2. Create configuration files - for setup

Devise also comes with a generator that allows us to configure the gem. Devise附带了一个generator,我们可以用它来配置the gem.This is similar to how we generated our Model for Categories and Products. This time we'll be using Devise's built in setup feature.

这次我们要用Devise的自带的setup feature.

[Instructions]

1. In your terminal,
rails generate devise:install which will create configuration files for us. Press Enter.

$ rails generate devise:install
create config/initializers/devise.rb
create config/locales/devise.en.yml
===============================================================================
$

3. Generate devise for user model and routes

In order to let users sign up for the app, we need a place to safely store their information.

我们在前面也见到这个问题,当我们需要一个地方来store category & product信息时,我们建立了Category & Product Models. 这里是一样的,把信息存在User Model里。devise 跟了一个命令就是拿来建立user model的,下面就要来了:

【Instructions】

1. In your terminal, type
rails generate devise user which will create our user model. Press Enter.

$ rails generate devise user
invoke active_record
create db/migrate/20141015022653_devise_create_users.rb
create app/models/user.rb
invoke test_unit
create test/models/user_test.rb
create test/fixtures/users.yml
insert app/models/user.rb
route devise_for :users
$

In addition to creating a User model, Devise also created a route to sign up new users. Let's see what
this route looks like.

***file:**config/routes.rb:

Rails.application.routes.draw do
get '/' => 'pages#home' resources :categories
get 'categories/:id/delete' => 'categories#delete', :as => :categories_delete resources :products
get 'products/:id/delete' => 'products#delete', :as => :products_delete devise_for :users #the routes for users created by advise
end

4. Migrate database

In our Model, we can see that Devise adds a number of words ending in 'able'. These are different functionalities that we can add to our app, like registering new users and remembering them.

In our Migration file, we can see that Devise has added new columns for each module it created. The Migration table works similar to the ones we created earlier, storing new features.

*** file: app/models/user.rb:

class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end

[Instructions]

1.In your terminal, run
bundle exec rake db:migrate to migrate your database. Press Enter.

$ bundle exec rake db:migrate
== 20140929235235 DeviseCreateUsers: migrating ================================
-- create_table(:users)
-> 0.0055s
-- add_index(:users, :email, {:unique=>true})
-> 0.0008s
-- add_index(:users, :reset_password_token, {:unique=>true})
-> 0.0025s
== 20140929235235 DeviseCreateUsers: migrated (0.0090s) =======================

5. Create our First User

Now that the User Model is set up, let's create our first user. This is similar to what we did earlier for Products and Categories.

We can do this by adding an email, password, and password_confirmation in seeds.rb:

user = User.create(email: 'name@name.com', password: 'password1', password_confirmation: 'password1')

Instructions

1.
In seeds.rb, on line 9, add seed data for an email, password, and
password_confirmation.

The password and password_confirmation must match. Hit Run.

在 ** db/seeds.rb 文件里,加入:

user = User.create(email: 'name@name.com', password: 'password1', password_confirmation: 'password1')

即添加了一个user.

2. In your terminal, run
rake db:seed to seed your database. Press Enter.(实际是: bundle exec rake db:seed)

$ bundle exec rake db:seed
$

6. Complete the TopNav view for costumers

Since our Users will be logging in through the home page we created earlier, we don't need to create separate views.

我们不需要再给用户建立一个登录的view,因为我们首页已经有了。如果不是这样的话,我们要给用户一个区分,看是不是已经登进去了:

i. If a User is signed in, we want to show the Sign Out link.

ii. If a User is signed out, we want to show links that allow users to Sign In or Sign Up.

我们就用if ... else ... 语句,在view里,来完成这个事儿。

1.Use an if statement to see if a user is signed in with their current user email. To do this line 27, check
if user_signed_in? On line 28, type current_user.email.

2.Use an else statement to display the sign in or sign up options. To do this add an
else statement on line 31, and an end statement on line 34.

file ** app/views/shared/_topnav.html.erb:

<!--=== Top ===-->
<div class="browse">
<div class="container">
<ul>
<li>Art</li>
<li>Home & Living</li>
<li>Jewelry</li>
<li>Books & Music</li>
<li>Women</li>
<li>Men</li>
<li>Kids</li>
<li>Vintage</li>
<li>Weddings</li>
<li>Crafts</li>
</ul>
</div>
</div> <div class="top">
<div class="container">
<div class="logo">
<img src="https://www.etsy.com/assets/dist/images/etsylogo.20140703190113.png">
</div>
<div>
<ul class="header-nav">
<% if user_signed_in? %><!--# add your if statement here %>-->
Logged in as <strong>
<%= current_user.email%> <!--# print out user email %>-->
</strong>.
<%= link_to "Sign out", destroy_user_session_path, method: :delete, :class => "btn btn-default" %>
<% else %> <!--#complete this %>-->
<%= link_to "Sign up", new_user_registration_path, :class => "btn btn-default" %>
<%= link_to "Sign in", new_user_session_path, :class => "btn btn-default" %>
<% end %> <!--#complete this %>-->
<li class="account">
<div class="cart pull-right">
<div class="fa fa-shopping-cart fa-2x">
</div>
</div>
</li>
</ul>
</div>
</div>

===================

7. 大结局

We're finally ready to try out our authentication system! In your browser try to sign in with your email and the password you stored in your seeds file.

In your browser, visit localhost:8000 and sign in with your email and encrypted password.

但是我们这里得到了一个 No Method Error:

一个错误的结局,就是下一步努力的开始。Yeah!但是我还是得到了Codecademy.com颁发的荣誉证书:

Ruby学习笔记7: 添加身份验证(adding Authentication)的更多相关文章

  1. Ruby学习笔记4: 动态web app的建立

    Ruby学习笔记4: 动态web app的建立 We will first build the Categories page. This page contains topics like Art, ...

  2. 用Retrofit发送请求中添加身份验证

    用Retrofit发送请求中添加身份验证====================在安卓应用开发中, retrofit可以极大的方便发送http网络请求,不管是GET, POST, 还是PUT, DEL ...

  3. 初识Identity并添加身份验证管理页面

    目录 初识Identity并添加身份验证管理页面 前言 什么是ASP.NET Core Identity 创建带有身份验证的WebApp 尝试运行 检查解决方案中的项目文件 发现问题 原因 解决问题 ...

  4. ruby学习笔记(1)-puts,p,print的区别

    ruby学习笔记-puts,p,print的区别 共同点:都是用来屏幕输出的. 不同点:puts 输出内容后,会自动换行(如果内容参数为空,则仅输出一个换行符号):另外如果内容参数中有转义符,输出时将 ...

  5. Django:学习笔记(9)——用户身份认证

    Django:学习笔记(9)——用户身份认证 User

  6. R语言可视化学习笔记之添加p-value和显著性标记

    R语言可视化学习笔记之添加p-value和显著性标记 http://www.jianshu.com/p/b7274afff14f?from=timeline   上篇文章中提了一下如何通过ggpubr ...

  7. 为WebService添加身份验证的两种方法

    方法一:SoapHeader 辅助类:MySoapHeader //SoapHeader 添加引用 using System.Web.Services.Protocols; #region 配置登录标 ...

  8. Ruby学习笔记6: 动态web app的建立(3)--多Model之间的交互

    We first built a static site which displayed a static image using only a Controller and a View. This ...

  9. Shiro学习(2)身份验证

    身份验证,即在应用中谁能证明他就是他本人.一般提供如他们的身份ID一些标识信息来表明他就是他本人,如提供身份证,用户名/密码来证明. 在shiro中,用户需要提供principals (身份)和cre ...

随机推荐

  1. 看图写代码---看图写代码 阅读<<Audio/Video Connectivity Solutions for Virtex-II Pro and Virtex-4 FPGAs >>

    看图写代码 阅读<<Audio/Video Connectivity Solutions for Virtex-II Pro and Virtex-4 FPGAs >> 1.S ...

  2. Android adb 模拟滑动 按键 点击事件

    模拟事件全部是通过input命令来实现的,首先看一下input命令的使用: usage: input ... input text <string>       input keyeven ...

  3. ALGO-39_蓝桥杯_算法训练_数组排序去重

    问题描述 输入10个整数组成的序列,要求对其进行升序排序,并去掉重复元素. 输入格式 10个整数. 输出格式 多行输出,每行一个元素. 样例输入 样例输出 解题思路: 若输入的数字存在数组中,剔除,否 ...

  4. uoj#119. 【UR #8】决战圆锥曲线

    http://uoj.ac/problem/119 可以认为数据基本随机,于是可以直接用线段树维护,对每个询问在线段树上进行剪枝搜索. #include<bits/stdc++.h> ty ...

  5. P1616疯狂的采药

    传送 它不是可爱的01背包了!!!这个题中一种药可以采无限次!!! 它进化成了完全背包.完全背包中的内循环从m到v[i]改成了从v[i]到m 既然如此,代码如下: #include<iostre ...

  6. 峰Redis学习(4)Redis 数据结构(List的操作)

    第四节:Redis 数据结构之List 类型 存储list: ArrayList使用数组方式 LinkedList使用双向链接方式   双向链接表中增加数据 双向链接表中删除数据   存储list常用 ...

  7. JVM异常之:栈溢出StackOverflowError

    在java虚拟机规范中,虚拟机栈和本地方法栈都会出现StackOverflowError和OutofMemoryError,程序计数器是java虚拟机中唯一一块不会产生error的内存区域. 一.St ...

  8. 廖雪峰Java4反射与泛型-3范型-5extends通配符

    1.泛型的继承关系: Pair<Integer>不是Pair<Number>的子类 add()不接受Pair<Integer> Pair.java package ...

  9. Zabbix 课程大纲

    Zabbix 课程笔记  day1 Zabbix 安装  day1 Zabbix 添加主机 day1 Zabbix 创建监控项目 day1 Zabbix 创建触发器 day1 Zabbix 告警内容配 ...

  10. go语言学习--map的并发

    go提供了一种叫map的数据结构,可以翻译成映射,对应于其他语言的字典.哈希表.借助map,可以定义一个键和值,然后可以从map中获取.设置和删除这个值,尤其适合数据查找的场景.但是map的使用有一定 ...