2011-05-07 104 views
3

我讓我的管理員用戶使用Michael Hartl's Rails 3 Tutorial。我這樣做是爲了讓我的管理員用戶只能看到所有用戶的Index.html.erb。那麼,如何讓我的鏈接僅由我的管理員用戶查看?如何只允許管理員查看鏈接

這是什麼在我的UsersController:

before_filter :authenticate, :only => [:destroy,:index,:show,:edit, :update] 
before_filter :correct_user, :only => [:edit, :update] 
before_filter :admin_user, :only => [:index,:destroy] 
. 
. 
. 
. 
private 
. 
. 
.  
def admin_user 
    authenticate 
    redirect_to(root_path) unless current_user.admin? 
end 

這就是我想要編輯管理員只看到:

<% if signed_in? %>   
     <%= link_to "Users", users_path %> 
<% end %> 
+0

Wallinzi,你的問題有點含糊。您的意思是檢查用戶是否爲admin的實際代碼,或者您是否想知道如何編寫單元或集成測試。 無論如何,我們可能需要了解您的用戶模型,以便我們知道您如何識別管理員,以便正確回答此問題。 – edgerunner 2011-05-07 19:21:59

+0

不要擔心測試,我會編輯我的問題以獲得更多解釋。 – LearningRoR 2011-05-07 20:14:31

回答

6

寫了一個helper方法,使你的意見是乾淨和可讀性。

your_view.html.erb

<% link_to "Users", users_path if admin? %> 

helpers/application_helper.rb

def admin? 
    @current_user.name == "Mr.Wallinzi" 
    # I made up the line above. Implement your own checks according to your setup 
end 
+0

謝謝你這個工作。 – LearningRoR 2011-05-07 21:04:48

1

我用ACCOUNT_TYPE作爲用戶的屬性。所以我寫了類似

def is_admin 
    return true if self.account_type == 1 #The admin account type 
end 

所以......

<%if signed_in? && @active_user.is_admin %>  
    <%= link_to "Users", users_path %></div> 
<% end %> 
+0

這是針對整個網站的1個管理員?唯一的管理員將是我。 – LearningRoR 2011-05-07 19:12:16

+0

這實際上取決於你如何辨別管理員 – 2011-05-07 19:14:10

+0

管理員充當用戶,但其他區域僅包含管理員(禁止用戶,刪除用戶等)。 – LearningRoR 2011-05-07 19:16:42

0

如果使用Devise,你可以很容易實現,在幾行字:

1-添加admin屬性設計表:

a。您可以使用遷移來添加它:$ rails generate migration add_admin_to_users admin:boolean。您的遷移現在看起來像這樣:

class AddAdminToUsers < ActiveRecord::Migration 
    def change 
     add_column :users, :admin, :boolean, :default => false 
    end 
    end 

b。添加admin?後製定的表就變得類似於email和其他屬性

<%= link_to "Users", users_path if current_user.admin? %> 

:另外,您可以在遷移前t.boolean :admin, null: false, default: false添加到設備表

2。在你看來,你可以在此如此。它以問號?結尾,因爲它是一個布爾類型。

相關問題