2016-01-27 25 views
2

我已經使用Devise + CanCanCan + rolify Tutorial構建了Ruby On Rails應用程序。Ruby On Rails Rolify + CanCanCan + Devise允許用戶只編輯他們的帖子

這裏是我的Ability型號:

class Ability 
    include CanCan::Ability 

    def initialize(user) 
    user ||= User.new # guest user (not logged in) 
    if user.has_role? :admin 
     can :manage, :all 
    else 
     can :read, :all 
    end 
    end 
end 

我想允許用戶編輯自己的帖子,被別人看的帖子。

我怎麼能做到這一點?

回答

4

你只需要到user_id傳遞給hash conditions

#app/models/ability.rb 
class Ability 
    include CanCan::Ability 

    def initialize(user) 
    user ||= User.new # guest user (not logged in) 
    if user.has_role? :admin 
     can :manage, :all 
    else 
     can :manage, Post, user_id: user.id #-> CRUD own posts only 
     can :read, :all #-> read everything 
    end 
    end 
end 

這將允許您使用:

#app/views/posts/index.html.erb 
<%= render @posts %> 

#app/views/posts/_post.html.erb 
<% if can? :read, post %> 
    <%= post.body %> 
    <%= link_to "Edit", edit_post_path(post), if can? :edit, post %> 
<% end %> 
+1

太謝謝你了!像魅力一樣工作! –

+0

謝謝你,我有一天在類似的事情上度過了6個小時。 –

+0

那麼,我對一般的鐵軌上的紅寶石和紅寶石很新,我不知道如果沒有SO,我會做什麼(很明顯,我會閱讀文檔,但它會花費太多時間): ) –

2

我同意理查德·佩克的答案。但是,我只想指出,不需要爲迎賓用戶(未登錄)提供服務。在實例化新對象(即對象的構造函數)時調用初始化器。

因此,上述能力類可能如下:

#app/models/ability.rb 
class Ability 
include CanCan::Ability 

def initialize(user) 

    if user.has_role? :admin 
    can :manage, :all 
    else 
    can :manage, Post, user_id: user.id #-> CRUD own posts only 
    can :read, :all #-> read everything 
    end 
end 
end 
相關問題