about 4 years ago

系統:

Mac OS X Yosemite 10.10
Ruby 2.1.4
Rails 4.1.7

相關連結

Rails Admin ( https://github.com/sferik/rails_admin )
Devise ( https://github.com/plataformatec/devise )
Cancan ( https://github.com/ryanb/cancan )

安裝步驟如下

1. Gemfile 設定

添加必要的 gem 套件至 Gemfile 檔中

# Use Rails Admin
gem 'rails_admin'
gem 'devise'
gem 'cancan'
gem 'rails-i18n'
bundle install
rails g rails_admin:install
rails g devise:install

2. Devise 設定

在 config/environments/development.rb 和 config/environments/production.rb 中新增以下 code,在 production 中,:host 應該設定為你 app 實際的主機名稱。

config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }

在 config/routes.rb 設定 root url

devise_for :user, path_names: { sign_in: 'login', sign_out: 'logout', sign_up: 'signup' }
mount RailsAdmin::Engine => '', as: 'rails_admin'

將 flash messages 加入至 app/views/layouts/application.html.erb.

<p class="notice"><%= notice %></p>
<p class="alert"><%= alert %></p>

執行以下指令

rails g devise user
rake db:migrate

修改 /config/initializers/devise.rb

config.secret_key = 'can get from <rake secret>'
config.mailer_sender = 'youemail@demo.com'

登入登出方法

<% if current_user %>
  <%= link_to('登出', destroy_user_session_path, :method => :delete) %> |
  <%= link_to('修改密碼', edit_registration_path(:user)) %>
<% else %>
  <%= link_to('註冊', new_registration_path(:user)) %> |
  <%= link_to('登入', new_session_path(:user)) %>
<% end %>

如果想要修改 devise 的 views,可以執行以下指令,他會在 app/views/ 中生成 devise 的 views

rails generate devise:views

3. Cancan 設定

rails g cancan:ability

Handle Unauthorized Access

class ApplicationController < ActionController::Base
  rescue_from CanCan::AccessDenied do |exception|
    redirect_to main_app.rails_admin_path, :alert => exception.message
  end
end

4. 其他安裝設定

修改 /config/initializers/rails_admin.rb,去除 #

  ## == Devise ==

  config.authenticate_with do
    warden.authenticate! scope: :user
  end
  config.current_user_method(&:current_user)

  ## == Cancan ==

  config.authorize_with :cancan
← OS X EI Capitan 10.11.1 安裝設定 RVM + Ruby on Rails 設定 Rspec 測試環境 →
 
comments powered by Disqus