开发者

Restrict access to some model items in Rails 3

I have Post model with published? field and some authorization system which defines admin? method inside ApplicationController.

I want to restrict access to unpublished posts and show them only to administrator.

I tried to define a scope accessible to return only published posts to users, but all posts for administrator.

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

def self.accessible
  admin? ? all : published
end

The problem is that admin? method can't be accessed inside the model. Wha开发者_JS百科t is the best way to implement what I want?


# 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


One way, but not so abstract.

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

Post.published_unless(admin?)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜