2011-05-07 24 views
18

某些型號的屬性能力,我有一個郵政模型與:published屬性(布爾)和用戶模型與role屬性()。有三種角色:ROLES = %w[admin publisher author]慘慘:限制用戶對設置基於角色

我不想讓用戶的作用是作者應能設置,或編輯,在:published場對早報模型。

我使用的康康舞(和RailsAdmin GEM)和我的簡化Ability.rb文件看起來像這樣:

class Ability 
    include CanCan::Ability 
    def initialize(user) 
    user ||= User.new 

    if user.role? :admin 
     can :manage, :all 
    elsif user.role? :publisher 
     can :manage, Post 
    elsif user.role? :author 
     # I want to prevent these guys from setting the :published attribute 
    end 

    end 
end 

任何人有什麼祕訣做這樣的事情?

回答

13

到目前爲止,這是不可能的。但根據這個:https://github.com/ryanb/cancan/issues/326這個功能應該在cancan 2.0中。

更新:你可以看到這對慘慘2.0分支的位置:在部分https://github.com/ryanb/cancan/tree/2.0「資源屬性」

+0

好的,謝謝你,我會關注CanCan v2.0。謝謝 – stephenmurdoch 2011-05-07 14:34:11

+0

我知道這並不完美,但我認爲你仍然可以使用'can not << your attribute >>,:klass bee',因爲它們在等待2.0時仍然是ruby中的方法。 – 2012-12-22 06:51:06

0

有一種方法,我做了這樣的事情在我的項目。但CanCan並不完全是答案。你需要做的是根據用戶角色在模型動態中創建attr_accessible,所以如果你是管理員,那麼你可以更新發布的字段。如果不是這樣,那麼在模型保存時,給該字段一個新的值就不會採用。

Railscasts來救援再次:http://railscasts.com/episodes/237-dynamic-attr-accessible

繼獲得的是實施的後端部分,那麼你可以通過與角色查看包裹的發佈現場做一些前端形式支票或東西根據用戶顯示或隱藏字段。我執行的粗糙例子...

<% if current_user.roles.where(:name => ['Administrator','Editor']).present? %> 
    <%= f.label :display_name %> 
    <%= f.text_field :display_name %> 
<% end %> 
+0

謝謝,我喜歡這個 - 現在要去看那個railscast - 謝謝:) – stephenmurdoch 2011-05-08 13:46:14

3

退房這個帖子:How do I use CanCan with rails admin to check for ownership

它顯示瞭如何使場不可見基於掀起了用戶的角​​色。

UPDATE 我能夠設置選項中軌與此代碼管理:

config.model User do 
    edit do 
    configure :organization do 
     visible do 
     bindings[:view]._current_user.max_role_name != 'admin' ? false : true 
     end 
    end 

    configure :organization_id, :hidden do 
     visible do 
     true if bindings[:view]._current_user.max_role_name != 'admin' 
     end 
     default_value do 
     bindings[:view]._current_user.organization_id if bindings[:view]._current_user.max_role_name != 'admin' 
     end 
    end 

    include_all_fields 
    end 
end 

如果登錄用戶是不是管理員此配置將隱藏在組織領域。它會顯示一個organization_id字段(設置爲type ='hidden')並設置默認值。

希望這可以幫助別人。

+0

約翰古德曼? – 2013-05-08 21:32:21

3

直到CanCan 2。0出來的時候,我已經通過創建一個受限的無障礙模型的一個子類解決了這個,是這樣的:

class AuthorPost < Post 
    attr_protected :published 
end 

然後給作者訪問AuthorPosts:can :manage => AuthorPost

然後在您的控制器,可以設置所需的資源在的before_filter:

before_filter :set_resource 
... 
    private 
    def set_resource 
     if current_user and current_user.author? 
     @resource = AuthorPost 
     else 
     @resource = Post 
     end 
     params[:post] ||= params[:author_post] 
    end 

最後一個警告:你將無法在該控制器使用load_and_authorize_resource。您必須手動執行此操作,詳細信息如下:https://github.com/ryanb/cancan/wiki/Controller-Authorization-Example

您需要將替換爲@resource

我很想知道這是否比railscast中描述的方法更有效或更低效。出於我的目的,它完全保留了原來的模型,所以我的其他代碼不受影響 - 只允許我爲一些用戶提供更少的可編輯字段。