构建Devise用户体系
大家应该知道,我们在学习的时候,主要分为五个部分的维度,现在我们已经完成了二个维度的学习,其中包括技能功能,页面美化;
接下来我们所学习的就是用户体系,在用户体系下面,就是属于云端部署,我们在云端部署的时候,使用 Heroku 完成部署,其实在前一段的时候,我们已经完成了这个部分的教学,后期我们使用 阿里云 完成云端部署,给大家一些不一样的启迪。
安装gem: https://rubygems.org/
gem 'devise', '~> 4.4', '>= 4.4.1' https://rubygems.org/gems/devise
rails generate devise:install
Running via Spring preloader in process 1901 create config/initializers/devise.rb
create config/locales/devise.en.yml
===============================================================================
Some setup you must do manually if you haven't yet:
Ensure you have defined default url options in your environments files. Here is an example of default_url_options appropriate for a development environment in config/environments/development.rb:
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
In production, :host should be set to the actual host of your application.
Ensure you have defined root_url to something in your config/routes.rb. For example:
root to: "home#index"
Ensure you have flash messages in app/views/layouts/application.html.erb. For example:
<%= notice="" %="">
<%= alert="" %="">
You can copy Devise views (for customization) to your app by running:
rails g devise:views
===============================================================================
rails g devise:views
Running via Spring preloader in process 1955 invoke Devise::Generators::SharedViewsGenerator create app/views/devise/shared create app/views/devise/shared/links.html.erb invoke simple_form_for create app/views/devise/confirmations create app/views/devise/confirmations/new.html.erb create app/views/devise/passwords create app/views/devise/passwords/edit.html.erb create app/views/devise/passwords/new.html.erb create app/views/devise/registrations create app/views/devise/registrations/edit.html.erb create app/views/devise/registrations/new.html.erb create app/views/devise/sessions create app/views/devise/sessions/new.html.erb create app/views/devise/unlocks create app/views/devise/unlocks/new.html.erb invoke erb create app/views/devise/mailer create app/views/devise/mailer/confirmation_instructions.html.erb create app/views/devise/mailer/email_changed.html.erb create app/views/devise/mailer/password_change.html.erb create app/views/devise/mailer/reset_password_instructions.html.erb create app/views/devise/mailer/unlock_instructions.html.erb
rails g devise User
Running via Spring preloader in process 1988 invoke active_record create db/migrate/20180203063544_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
rake db:migrate
== 20180203063544 DeviseCreateUsers: migrating ================================ -- create_table(:users) -> 0.0037s -- add_index(:users, :email, {:unique=>true}) -> 0.0008s -- add_index(:users, :reset_password_token, {:unique=>true}) -> 0.0008s == 20180203063544 DeviseCreateUsers: migrated (0.0057s) =======================
在app/views/layouts/application.html.erb文件里面添加用户导航代码
<!DOCTYPE html>
<html>
<head>
<title>Messageapp</title>
<%= csrf_meta_tags %>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
</head>
<body>
<div class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<%= link_to "message board", root_path, class: "navbar-brand" %>
</div>
<ul class="nav navbar-nav">
<li><%= link_to "sign up", new_user_registration_path %></li>
<% if user_signed_in? %>
<li><%= link_to "sign out",destroy_user_session_path, method: :delete %></li>
<% else %>
<li><%= link_to "log in", new_user_session_path %></li>
<% end %>
</ul>
<% if user_signed_in? %>
<p><%= link_to "new_message", new_message_path, class: "navbar-right navbar-text navbar-link" %></p>
<% end %>
</div>
</div>
<p class="notice"><%= notice %></p>
<p class="alert"><%= alert %></p>
<%= yield %>
</body>
</html>
四、构建用户对应关系
git chekcout -b xw-020302
rails generate migration add_user_id_to_messages user_id:integer
Running via Spring preloader in process 6332 invoke active_record create db/migrate/20180203084514_add_user_id_to_messages.rb
rake db:migrate
== 20180203084514 AddUserIdToMessages: migrating ============================== -- add_column(:messages, :user_id, :integer) -> 0.0017s == 20180203084514 AddUserIdToMessages: migrated (0.0018s) =====================
atom .
rails c
Running via Spring preloader in process 6439 Loading development environment (Rails 5.1.4)
2.3.1 :001 > Message.connection
=> #
2.3.1 :003 > @message = Message.last
Message Load (0.3ms) SELECT "messages".* FROM "messages" ORDER BY "messages"."id" DESC LIMIT ? [["LIMIT", 1]]
=> #
2.3.1 :004 > exit
rails s
=> Booting Puma
=> Rails 5.1.4 application starting in development
=> Run `rails server -h` for more startup options
Puma starting in single mode...
* Version 3.11.2 (ruby 2.3.1-p112), codename: Love Song
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://0.0.0.0:3000
Use Ctrl-C to stop
rails c
Running via Spring preloader in process 6574
Loading development environment (Rails 5.1.4)
2.3.1 :001 > Message.connection
=> #<ActiveRecord::ConnectionAdapters::SQLite3Adapter:0x007fa4bb454a68 @transaction_manager=#<ActiveRecord::ConnectionAdapters::TransactionManager:0x007fa4bab813f0 @stack=[], @connection=#<ActiveRecord::ConnectionAdapters::SQLite3Adapter:0x007fa4bb454a68 ...>>, @query_cache={}, @query_cache_enabled=false, @connection=#<SQLite3::Database:0x007fa4bb4551c0 @tracefunc=nil, @authorizer=nil, @encoding=#<Encoding:UTF-8>, @busy_handler=nil, @collations={}, @functions={}, @results_as_hash=true, @type_translation=nil, @readonly=false>, @owner=#<Thread:0x007fa4ba883428 run>, @instrumenter=#<ActiveSupport::Notifications::Instrumenter:0x007fa4be398bf8 @id="0aadc5a44019b1e52824", @notifier=#<ActiveSupport::Notifications::Fanout:0x007fa4bb22f648 @subscribers=[#<ActiveSupport::Notifications::Fanout::Subscribers::Evented:0x007fa4bacca220 @pattern="sql.active_record", @delegate=#<ActiveRecord::LogSubscriber:0x007fa4bacca798 @queue_key="ActiveRecord::LogSubscriber-70172742669260", @patterns=["sql.active_record"]>, @can_publish=false>, #<ActiveSupport::Notifications::Fanout::Subscribers::Evented:0x007fa4be06a5a8 @pattern="logger.action_view", @delegate=#<ActionView::LogSubscriber:0x007fa4be06ac88 @root=nil, @queue_key="ActionView::LogSubscriber-70172769736260", @patterns=["logger.action_view", "render_partial.action_view", "render_template.action_view", "render_collection.action_view"]>, @can_publish=false>, #<ActiveSupport::Notifications::Fanout::Subscribers::Evented:0x007fa4be06a2d8 @pattern="render_partial.action_view", @delegate=#<ActionView::LogSubscriber:0x007fa4be06ac88 @root=nil, @queue_key="ActionView::LogSubscriber-70172769736260", @patterns=["logger.action_view", "render_partial.action_view", "render_template.action_view", "render_collection.action_view"]>, @can_publish=false>, #<ActiveSupport::Notifications::Fanout::Subscribers::Evented:0x007fa4be069f90 @pattern="render_template.action_view", @delegate=#<ActionView::LogSubscriber:0x007fa4be06ac88 @root=nil, @queue_key="ActionView::LogSubscriber-70172769736260", @patterns=["logger.action_view", "render_partial.action_view", "render_template.action_view", "render_collection.action_view"]>, @can_publish=false>, #<ActiveSupport::Notifications::Fanout::Subscribers::Evented:0x007fa4be069c20 @pattern="render_collection.action_view", @delegate=#<ActionView::LogSubscriber:0x007fa4be06ac88 @root=nil, @queue_key="ActionView::LogSubscriber-70172769736260", @patterns=["logger.action_view", "render_partial.action_view", "render_template.action_view", "render_collection.action_view"]>, @can_publish=false>, #<ActiveSupport::Notifications::Fanout::Subscribers::Evented:0x007fa4bb4fe608 @pattern="sql.active_record", @delegate=#<ActiveRecord::ExplainSubscriber:0x007fa4bb4fe680>, @can_publish=false>], @listeners_for=#<Concurrent::Map:0x007fa4bb22f5d0 entries=2 default_proc=nil>, @mutex=#<Thread::Mutex:0x007fa4bb22f440>>>, @logger=#<ActiveSupport::Logger:0x007fa4be49b028 @progname=nil, @level=0, @default_formatter=#<Logger::Formatter:0x007fa4be49af88 @datetime_format=nil>, @formatter=#<ActiveSupport::Logger::SimpleFormatter:0x007fa4badb1468 @datetime_format=nil>, @logdev=#<Logger::LogDevice:0x007fa4be49af10 @shift_size=nil, @shift_age=nil, @filename=nil, @dev=#<File:/Users/xiaowei/messageapp/log/development.log>, @mon_owner=nil, @mon_count=0, @mon_mutex=#<Thread::Mutex:0x007fa4be49aec0>>, @local_levels=#<Concurrent::Map:0x007fa4be49ada8 entries=0 default_proc=nil>>, @config={:adapter=>"sqlite3", :pool=>5, :timeout=>5000, :database=>"/Users/xiaowei/messageapp/db/development.sqlite3"}, @pool=#<ActiveRecord::ConnectionAdapters::ConnectionPool:0x007fa4bb7bb440 @mon_owner=nil, @mon_count=0, @mon_mutex=#<Thread::Mutex:0x007fa4bb7bb350>, @query_cache_enabled=#<Concurrent::Map:0x007fa4bb7bb328 entries=0 default_proc=#<Proc:0x007fa4bb7bb2d8@/Users/xiaowei/.rvm/gems/ruby-2.3.1/gems/activerecord-5.1.4/lib/active_record/connection_adapters/abstract/query_cache.rb:27>>, @spec=#<ActiveRecord::ConnectionAdapters::ConnectionSpecification:0x007fa4bb7bb5a8 @name="primary", @config={:adapter=>"sqlite3", :pool=>5, :timeout=>5000, :database=>"/Users/xiaowei/messageapp/db/development.sqlite3"}, @adapter_method="sqlite3_connection">, @checkout_timeout=5, @reaper=#<ActiveRecord::ConnectionAdapters::ConnectionPool::Reaper:0x007fa4bb7bb260 @pool=#<ActiveRecord::ConnectionAdapters::ConnectionPool:0x007fa4bb7bb440 ...>, @frequency=nil>, @size=5, @thread_cached_conns=#<Concurrent::Map:0x007fa4bb7bb210 entries=1 default_proc=nil>, @connections=[#<ActiveRecord::ConnectionAdapters::SQLite3Adapter:0x007fa4bb454a68 ...>], @automatic_reconnect=true, @now_connecting=0, @threads_blocking_new_connections=0, @available=#<ActiveRecord::ConnectionAdapters::ConnectionPool::ConnectionLeasingQueue:0x007fa4bb7bb170 @lock=#<ActiveRecord::ConnectionAdapters::ConnectionPool:0x007fa4bb7bb440 ...>, @cond=#<MonitorMixin::ConditionVariable:0x007fa4bb7bb0f8 @monitor=#<ActiveRecord::ConnectionAdapters::ConnectionPool:0x007fa4bb7bb440 ...>, @cond=#<Thread::ConditionVariable:0x007fa4bb7bb0d0>>, @num_waiting=0, @queue=[]>, @lock_thread=false>, @schema_cache=#<ActiveRecord::ConnectionAdapters::SchemaCache:0x007fa4bab811c0 @connection=#<ActiveRecord::ConnectionAdapters::SQLite3Adapter:0x007fa4bb454a68 ...>, @columns={}, @columns_hash={}, @primary_keys={}, @data_sources={}>, @quoted_table_names={}, @quoted_column_names={}, @visitor=#<Arel::Visitors::SQLite:0x007fa4bab80ec8 @dispatch={}, @connection=#<ActiveRecord::ConnectionAdapters::SQLite3Adapter:0x007fa4bb454a68 ...>>, @lock=#<Monitor:0x007fa4bab80d60 @mon_owner=nil, @mon_count=0, @mon_mutex=#<Thread::Mutex:0x007fa4bab80d10>>, @prepared_statements=true, @active=nil, @statements=#<ActiveRecord::ConnectionAdapters::SQLite3Adapter::StatementPool:0x007fa4bab80ba8 @cache={}, @statement_limit=1000>>
2.3.1 :002 > @message = Message.last
Message Load (0.4ms) SELECT "messages".* FROM "messages" ORDER BY "messages"."id" DESC LIMIT ? [["LIMIT", 1]]
=> #<Message id: 8, title: "dd", description: "fdfdf", created_at: "2018-02-03 08:51:37", updated_at: "2018-02-03 08:51:37", user_id: 1>
2.3.1 :003 > @message = Message.first
Message Load (0.3ms) SELECT "messages".* FROM "messages" ORDER BY "messages"."id" ASC LIMIT ? [["LIMIT", 1]]
=> #<Message id: 1, title: "rew", description: "rwer", created_at: "2018-02-03 08:21:40", updated_at: "2018-02-03 08:21:40", user_id: nil>
2.3.1 :004 > @message.user_id = 1 => 1 2.3.1 :005 > @message.save
(0.2ms) begin transaction
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
SQL (0.6ms) UPDATE "messages" SET "updated_at" = ?, "user_id" = ? WHERE "messages"."id" = ? [["updated_at", "2018-02-03 08:54:49.223632"], ["user_id", 1], ["id", 1]]
(1.1ms) commit transaction
=> true
2.3.1 :006 > @message = Message.find(3)
Message Load (0.5ms) SELECT "messages".* FROM "messages" WHERE "messages"."id" = ? LIMIT ? [["id", 3], ["LIMIT", 1]]
=> #<Message id: 3, title: "werwerw", description: "rwrwerwr", created_at: "2018-02-03 08:21:48", updated_at: "2018-02-03 08:21:48", user_id: nil>
2.3.1 :007 > @message.user_id = 1 => 1 2.3.1 :008 > @message.save
(0.1ms) begin transaction
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
SQL (0.5ms) UPDATE "messages" SET "updated_at" = ?, "user_id" = ? WHERE "messages"."id" = ? [["updated_at", "2018-02-03 08:56:41.568721"], ["user_id", 1], ["id", 3]]
(9.0ms) commit transaction
=> true
2.3.1 :009 > @message = Message.find(4)
Message Load (0.2ms) SELECT "messages".* FROM "messages" WHERE "messages"."id" = ? LIMIT ? [["id", 4], ["LIMIT", 1]]
=> #<Message id: 4, title: "rr", description: "rwrwe", created_at: "2018-02-03 08:22:33", updated_at: "2018-02-03 08:22:33", user_id: nil>
2.3.1 :010 > @message.user_id = 1 => 1 2.3.1 :011 > @message.save
(0.1ms) begin transaction
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
SQL (0.4ms) UPDATE "messages" SET "updated_at" = ?, "user_id" = ? WHERE "messages"."id" = ? [["updated_at", "2018-02-03 08:57:34.826474"], ["user_id", 1], ["id", 4]]
(9.0ms) commit transaction
=> true
2.3.1 :012 > exit
rails s
=> Booting Puma
=> Rails 5.1.4 application starting in development
=> Run rails server -h
for more startup options
Puma starting in single mode...
- Version 3.11.2 (ruby 2.3.1-p112), codename: Love Song
- Min threads: 5, max threads: 5
- Environment: development
- Listening on tcp://0.0.0.0:3000 Use Ctrl-C to stop
肖威 2018.02.14