Rails 的超小型筆記 (3)


1
2
3
4
5
6
# Devise 登出無效
1. rake routes 查看提交的方法確定是 DELETE
2. 所以使改登出方法為 :method => :delete

<%= link_to(t(".logout"), destroy_user_session_path, :method => :delete) %>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
	
# Devise 以 username 或 email 登入
1. app/modles/user.rb 加入,其中 :username_or_email 可自定

# 可讀寫的欄位並且他是一個虛擬欄位,不存在於真實資料庫中
attr_accessible :username_or_email
attr_accessor :username_or_email

# 覆寫原來的 Devise 方法
protected

def self.find_for_database_authentication(warden_conditions)
conditions = warden_conditions.dup
username_or_email = conditions.delete(:username_or_email)
where(conditions).where(["lower(username) = :value OR lower(email) = :value", { :value => username_or_email.downcase }]).first
end

2. config/initializers/devise.rb 打開 authentication_keys 為

# 添加驗證欄位 :username_or_email
config.authentication_keys = [ :username_or_email ]

3. 修改 app/views/devise/sessions/new.html.erb

# 刪除
<p><%= f.label :email %><br />
<%= f.email_field :email %></p>

# 加入
<p><%= f.label :username_or_email %><br />
<%= f.email_field :username_or_email %></p>

4. 打開 config/locales/zh-TW.yml 添加這個欄位的語言 path

zh-TW:
activerecord:
username_or_email: "用名名/電郵"

5. 打開 config/locales/devise.zh-TW.yml 修改錯誤信息為

zh-TW:
devise:
failure:
invalid: '用戶名/電郵地址/密碼是無效的。'

6. 重新 Start WebServer
1
2
3
4
5
6
7
8
9
   
# Rails Admin 中缺少 i18n 的 language 語系檔案
1. 注解掉 config/application.rb 中的這行

config.i18n.default_locale = "zh-TW"

2. 於 config/locales 下面建立 admin.zh-TW.yml 則可
3. 相關語系可以暫用簡轉繁
4. 重新 Start WebServer
1
2
# 刪除 Generator 生成出來的相關檔案
rails destroy [Generator] [檔案]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# Devise 中增加 role 身份
1. rails generate migration add_admin_to_users_table
2. 修改 db/migrate/[date]_add_admin_to_users_table.rb 為

class AddAdminToUsersTable < ActiveRecord::Migration
def self.up
add_column :users, :admin, :boolean, :default => false
end

def self.down
remove_column :users, :admin
end
end

3. rake db:migrate
4. 建立 config/initializer/rails_admin.rb 內容為

RailsAdmin.config do |config|
config.authorize_with do
redirect_to '/' unless current_user.try(:admin?)
end
end
1
2
3
4
5
6
7
# Rails Admin 中 No route matches {:controller=>"home"}
1. 不知道原因為什麼指定了 routes.rb 也不行,只能夠用比較欄的解法
2. 只好將 redirect_to root_path unless current_user.try(:admin?) 改為以下

redirect_to '/' unless current_user.try(:admin?)

3. 他會一直身處於 rails_admin 底下改 home 控制器
1
2
3
4
5
# 將 id 為 1 的帳號升格為 admin
rails c
row = User.find(1)
row.admin = true
row.save
1
2
3
4
# Rails Admin 的感覺
1. 文檔相對於 Devise 來說是比較差的
2. 缺少語系檔的支援.而且好像不能是 前台中文 後台定為英文?
2. 更加重要的是可以自定的東西太少了.所以最後放棄自己寫好了
1
2
3
# Migrate Up/Down
rake db:migrate:up VERSION=20110905124308 執行特定版本的Migration
rake db:migrate:down VERSION=20110905124308 回復特定版本的Migration