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

pav*_*jel 3 ruby-on-rails devise rolify cancancan

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

这是我的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
Run Code Online (Sandbox Code Playgroud)

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

我怎样才能做到这一点?

Ric*_*eck 5

您只需将 传递user_idhash 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
Run Code Online (Sandbox Code Playgroud)

这将允许您使用:

#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 %>
Run Code Online (Sandbox Code Playgroud)