代码之家  ›  专栏  ›  技术社区  ›  Simon Perepelitsa

限制对Rails 3中某些模型项的访问

  •  1
  • Simon Perepelitsa  · 技术社区  · 14 年前

    我有 Post 模型 published? admin? 方法内部 ApplicationController .

    我想限制对未发布的帖子的访问,并且只向管理员显示它们。

    accessible 仅向用户返回已发布的帖子,但向管理员返回所有帖子。

    scope :published, where(:published => true)
    
    def self.accessible
      admin? ? all : published
    end
    

    问题是 管理员? 方法无法在模型内部访问。实现我想要的最好的方法是什么?

    2 回复  |  直到 14 年前
        1
  •  2
  •   yfeldblum    14 年前
    # 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
  •  0
  •   Simon Perepelitsa    14 年前

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

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