【问题标题】:Ruby On Rails Rolify + CanCanCan + Devise allow user to edit only their postsRuby On Rails Rolify + CanCanCan + Devise 允许用户只编辑他们的帖子
【发布时间】:2016-01-27 14:33:58
【问题描述】:

我已经使用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

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

我怎样才能做到这一点?

【问题讨论】:

    标签: ruby-on-rails devise cancancan rolify


    【解决方案1】:

    您只需将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 %>
    

    【讨论】:

    • 非常感谢!像魅力一样工作!
    • 谢谢,前几天我花了大约 6 个小时在类似的事情上。
    • 好吧,总的来说,我对 ruby​​ 和 ruby​​ on rails 还是很陌生,我不知道没有 SO 我会怎么做(显然,我读过文档,但它d花费太多时间):)
    • 老实说,这些文档最适合参考;如果你想实现特定的目标,看看别人做了什么会更有效率
    • 它在我的情况下不起作用(Rails 6.0.3.2),链接“if can? :edit, post”的一部分导致视图崩溃。但另一方面,我不知道如何修复它以使其正常工作。把 before link 使“编辑”在它不应该出现时出现,点击它会给出“您无权访问此页面。”
    【解决方案2】:

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

    因此,上述能力类可以如下:

    #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
    

    【讨论】:

      猜你喜欢
      • 2014-03-14
      • 1970-01-01
      • 2013-04-06
      • 2017-11-10
      • 2015-03-09
      • 2015-05-28
      • 2015-10-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多