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

8
我已经开始使用Devise和CanCan创建一个Rails应用程序。我的用户与文章之间有一对多的关系。我对CanCan不熟悉,这是我的计划:
管理员: - 可以对文章执行任何操作
登录用户: - 可以阅读和创建文章 - 可以编辑和删除自己的文章
访客用户: - 可以阅读文章
但我很难理解CanCan的语法。我知道它大致应该是这样的:
def initialize(user)
  user ||= User.new
  if user.admin?
    can :manage, Article
  else
    can :read, Article
  end
end

但这只适用于管理员和访客用户,我不确定如何区分访客用户和已登录用户,因为当用户为空时会创建一个新的User对象。我看到代码应该像这样: can [:edit, :destroy], Article, :user_id => user.id,但我不确定这如何适用于initialize方法。
最后一个问题,如果我只对访客定义了can :read, Article,是否会阻止其他操作,比如创建和更新,就像白名单中的读取操作一样?
任何帮助都将不胜感激。非常感谢!
2个回答

22

以下是我所做的事情:

在 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

用以下代码来显示链接:

- 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?' }

现在似乎已经可以工作了,不确定这是否是最好的方法。


视图看起来不好,但与问题主题无关,该主题在你的ability.rb中似乎已经很好地涵盖了。 - denis.peplin
我使用自己编写的辅助函数,例如link_to_edit、link_to_destroy等。我的辅助函数包括对can?()方法的调用,因此无需在视图中放置逻辑。 - denis.peplin

8

我在@mumble编辑问题的同时添加了这个评论,现在问题已经包含答案。 - denis.peplin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接