views:

45

answers:

2

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. What is the best way to implement what I want?

+1  A: 
# 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
Justice
Good for applications with multiple users, but I don't have any registered users except me as administrator. I will search for prettier solution.
Semyon Perepelitsa
A: 

One way, but not so abstract.

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

Post.published_unless(admin?)
Semyon Perepelitsa