【问题标题】:Cancan and polymorphism康康和多态性
【发布时间】:2014-05-23 05:00:14
【问题描述】:

我想在能力文件中为多态关联指定规则如下:

 class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new # guest user

    if user.role? :admin
      can :manage, :all
    elsif user.role? :author
      can :read, :all
      can :manage, [Post, Article], user_id: user.id
      can :manage, Comment, commentable: {user_id: user.id}        
    end
  end
end

我希望用户能够编辑对其帖子的评论。但是在检查访问时,简单用户仍然可以编辑其他(所有)cmets。

这个技能对康康有效吗?

 can :manage, Comment, commentable: {user_id: user.id}        

感谢您的帮助!

======= 更新 =======

对不起,我忘了展示我的能力检查:

- can? :manage, @post => Comment

并试图重写:

= can? :manage, @post.comments.build

但我不喜欢这种检查,因为创建了空对象

【问题讨论】:

    标签: ruby-on-rails ruby polymorphism cancan polymorphic-associations


    【解决方案1】:

    documentation 表示只要您有一个名为commentable 的关联,您使用的声明就应该有效。当您使用该语法时,您仍然可以访问不拥有相关评论的用户吗? 问题可能出在能力检查上吗?

    更新

    问题在于你的能力检查。您正在检查用户是否可以管理任何评论。您需要检查他们是否可以更新(或根据您的喜好管理)他们尝试更新的特定评论。

    【讨论】:

    • 对不起,我忘了显示我的能力检查,请参阅问题更新
    • 那是你的问题。您正在检查管理通用评论的能力,而不是用户尝试更新的特定评论。当用户想要编辑它时,您需要做一些类似于can? :update, @comment 的操作。
    猜你喜欢
    • 2012-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多