【问题标题】:Field level permissions using CanCanCan or Pundit使用 CanCanCan 或 Pundit 的字段级权限
【发布时间】:2016-01-16 00:23:32
【问题描述】:

我目前正在使用带有 CanCanCan 1.13.1 的 Rails 4.1.14,并在模型/记录级别定义了细粒度权限。管理员可以管理所有文章,但用户只能编辑他们创作的文章。

为了防止普通用户编辑特定字段,我根据角色使字段在 rails_admin 中可见。

visible do 
  bindings[:object].id == bindings[:view].current_user.roles.include? :admin
end

我还在使用https://github.com/aasm/aasm gem 并创建了自定义操作,以便用户可以将记录移动到新状态。

但我真正想要的是根据用户的角色/记录启用字段级权限。我在 CanCanCan 或 https://github.com/elabs/pundit 页面上找不到任何文档。

有人有这方面的经验吗?

【问题讨论】:

    标签: ruby-on-rails-4 devise rails-admin pundit cancancan


    【解决方案1】:

    您的意思是应该允许管理员编辑记录的所有字段,但编辑者只能更改字段 x 和 y?

    是的,这在 pundit 中是可能的,因为它集成了强大的参数(无论如何您都应该使用)。 pundit readme 中还有一个示例(请参阅:强参数)。我从自述文件中简化了示例:

    # post_policy.rb
    def permitted_attributes
      if user.admin?
      [:title, :body, :tag_list]
    else
      [:tag_list]
    end
    
    # posts_controller.rb
    @post.update_attributes(permitted_attributes(@post))
    

    控制器中的permitted_attributes 助手由权威人士提供,并自动调用推断策略的permitted_attributes 方法。

    【讨论】:

    • 简单而出色的解决方案
    猜你喜欢
    • 1970-01-01
    • 2013-12-22
    • 1970-01-01
    • 2021-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多