CanCan - 如何允许用户仅更新和删除自己的对象

ger*_*rky 6 authentication authorization ruby-on-rails devise cancan

我已经用Devise和CanCan开始了一个Rails应用程序.我的用户与文章有一对多的关系.我是CanCan的新手,这是我打算做的事情:

管理员

  • 可以对文章做任何动作

登录用户

  • 可以阅读和创建文章
  • 可以编辑和销毁自己的文章

访客用户

  • 可以阅读文章

但我无法理解CanCan的语法.我明白它会是这样的.

def initialize(user)
  user ||= User.new
  if user.admin?
    can :manage, Article
  else
    can :read, Article
  end
end
Run Code Online (Sandbox Code Playgroud)

但这仅适用于管理员和访客用户,我不确定如何区分访客用户和登录用户,因为它在用户为空时创建新的用户对象.我已经看到代码应该是这样的can [:edit, :destroy], Article, :user_id => user.id,但我不确定这将如何适合初始化方法.

最后一个问题,如果我只定义一个can :read, Articleon guest,它是否会阻止其他操作,如创建和更新,如白色列出读取操作?

任何帮助,将不胜感激.非常感谢!

ger*_*rky 16

这是我做的:

在ability.rb

def initialize(user)
  if user.nil?
    can :read, Article
  elsif user.admin?
    can :manage, Article
  else
    can [:read, :create], Article
    can [:update, :destroy], Article, :user_id => user.id
  end
end
Run Code Online (Sandbox Code Playgroud)

为了显示链接,我使用了这个:

- if can? :read, Article
  = link_to 'Show', article
- if can? :create, Article
  = link_to 'New Article', new_article_path
- if can? :update, article
  = link_to 'Edit', edit_article_path(article)
- if can? :destroy, article
  = link_to 'Destroy', article, method: :delete, data: { confirm: 'Are you sure?' }
Run Code Online (Sandbox Code Playgroud)

它似乎现在正在工作,不知道这是否是最好的方式.


den*_*lin 8

您可以传递条件的哈希值:

can :manage, Article, :user_id => user.id
Run Code Online (Sandbox Code Playgroud)

有关详细信息,查看https://github.com/ryanb/cancan/wiki/defining-abilities.