Ruby On Rails Rolify + CanCanCan + Devise允许用户只编辑他们的帖子

时间:2016-01-27 14:33:59

标签: ruby-on-rails devise cancancan rolify

我使用Devise + CanCanCan + rolify Tutorial构建了Ruby On Rails个应用程序。

这是我的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

我想允许用户编辑自己的帖子,并阅读其他人的帖子。

我怎么能实现这个目标?

2 个答案:

答案 0 :(得分: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 :(得分:2)

我同意Richard Peck的回答。但是,我只想指出,不需要为访客用户(未登录)提供服务。在实例化新对象(即对象的构造函数)时调用初始化程序。

因此,上述Ability类可以如下:

#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