【问题标题】:Restrict access to some model items in Rails 3限制对 Rails 3 中某些模型项的访问
【发布时间】:2010-08-09 18:51:24
【问题描述】:

我有带有published? 字段的Post 模型和一些在ApplicationController 中定义admin? 方法的授权系统。

我想限制对未发布帖子的访问并仅向管理员显示。

我尝试定义一个范围 accessible 以仅将已发布的帖子返回给用户,但将所有帖子返回给管理员。

scope :published, where(:published => true)

def self.accessible
  admin? ? all : published
end

问题是模型内部无法访问admin? 方法。实现我想要的最佳方式是什么?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3


    【解决方案1】:
    # option 1
    class Post < ActiveRecord::Base
      def self.accessible_to user
        user.admin? ? all : published
      end
    end
    class PostsController < ApplicationController
      def index
        @posts = post.accessible_to current_user
      end
    end
    
    # option 2
    class Post < ActiveRecord::Base
      def self.accessible is_admin
        is_admin ? all : published
      end
    end
    class PostsController < ApplicationController
      def index
        @posts = post.accessible admin?
      end
    end
    

    【讨论】:

    • 适用于具有多个用户的应用程序,但除了我作为管理员之外,我没有任何注册用户。我会寻找更漂亮的解决方案。
    【解决方案2】:

    一种方式,但不是那么抽象。

    def self.published_unless(condition)
      condition ? all : published
    end
    
    Post.published_unless(admin?)
    

    【讨论】:

      猜你喜欢
      • 2020-01-14
      • 2012-05-19
      • 2015-10-14
      • 2016-07-07
      • 2012-09-29
      • 1970-01-01
      • 2022-11-26
      • 1970-01-01
      • 2021-10-08
      相关资源
      最近更新 更多