我想你需要設置一些授權機制。
我知道的最好的寶石是declarative_authorization。我個人在生產環境中使用過它,我對它感到滿意。關於它也有一個railscast。
這個想法是你在一個特定的文件(config/authorization_rules.rb
)中聲明「角色和權限」。你說諸如「經理只能讀取與之相關的客戶端」或「管理員可以讀寫所有用戶」。在你的情況下,它應該是這樣的:
authorization do
role :guest do
# actions here can be done by everyone, even not logged in people
end
role :user do
includes :guest
# actions here can be done by logged people
end
role :manager do
includes :user #managers do everything users do, plus:
has_permission_on :sales_region, :to => :read do
if_attribute :id => is_in {user.sales_region_ids}
end
has_permission_on :users, :to => [:update, :read] do
if_attribute :id => is {user.user_ids_by_sales_region} #defined on the model
end
end
role :admin do
includes :user
has_permission_on [:sales_regions, :users], :to :manage
end
end
privileges do
privilege :manage do
includes :create, :read, :update, :delete
end
end
一旦這個規定,你必須讓他們使用declarative_authorization
修改模型。此外,讓我們定義user_ids_by_sales_region
方法
class User < ActiveRecord::Base
using_access_control # this enables DA
def users_by_sales_region
sales_regions.collect{ |sr| sr.users }.flatten.uniq
end
def user_ids_by_sales_region
users_by_sales_region.collect{ |u| u.id }
end
end
你還必須有一個current_user
方法,並獲取當前用戶的角色(一個或多個)的一種方式。請參閱readme上的「提供插件的要求」一節。
然後,你可以做你想要什麼with_permissions_to
:
manager = User.find(...)
manager.users.with_permissions_to(:read) # the users from his region
manager.users.with_permissions_to(:read).find(:all, conditions => { :active => true })
manager.users.with_permissions_to(:write) #returns no users, managers can't edit them
admin = User.find(...)
admin.users.with_permissions_to(:write) #will return all users
這意味着在開始一點點努力,但大大後來就簡化了應用。此外,您還有其他功能,例如根據當前用戶的權限隱藏/顯示部分視圖,以及禁止訪問特定的控制器操作。
而且,它應該工作只是罰款paginations等
有一個稱爲cancan另一種聲明授權寶石。我沒有這方面的經驗,但是如果是由瑞安貝茨完成的話,那一定很好(他也有這個railscast)。但是,我不認爲它允許模型擴展,這是你現在需要的。
感謝您的回答,當然看起來像一個偉大的插件。 我最終試圖在需要限制的模型上聲明named_scopes,以便可以使用(例如)User.visible_to(@current_user)或Account.visible_to(@current_user).in_sales_area(3)來訪問它們。我會在下面發佈一些示例代碼。 再次感謝! – 2010-02-04 14:51:13