---
# System prepended metadata

title: devise 安裝
tags: [安裝套件 相關]

---

---
title:  devise 安裝
tags: 安裝套件 相關
---

## <font color=red>**devise 安裝** </font>

```ruby=
gem 'devise'
# 安裝套件

rails g devise:install

rails g devise user
# 新增 user model
# 調整migration

rails g devise:views
# 產生html樣板
rails db:migrate

rails g controller users
before_action :authenticate_user!
# 在需要登入的 controller 加入
```
```ruby=
config/environments/development.rb
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
# 增加寄信預設網址

app/views/layouts/application.html.erb
<p class="notice"><%= notice %></p>
<p class="alert"><%= alert %></p>
# 全部頁面都能顯示flash

root :to => "controller#method"
# 設定首頁

<% 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 %>
# 全部頁面都加入登入登出超連結
```
```ruby=
# 新增自訂欄位，先添加migration
# application_controller.rb補上configure_permitted_parameters方法

class ApplicationController < ActionController::Base
    before_action :configure_permitted_parameters, if: :devise_controller?



    privated

    def configure_permitted_parameters
        devise_parameter_sanitizer.permit(:sign_up, keys: [:nickname])
        devise_parameter_sanitizer.permit(:account_update, keys: [:nickname])
    end
end

# 新增view表單欄位
```