You can add a method to the BaseController, and call it in each action that should have this restriction. Something like this:
in base_controller.rb:
protected
def filtered_users
if settings.api_group
User.where(:group_id => settings.group_id)
else
User.scoped
end
end
and in the controllers that inherit from it:
def index
@users = filtered_users
end
This way, you only define the filtering in one place. If it needs to change later, you only have to change it in one place. Because filtered_users
actually returns a Relation, you can continue to alter the query by tacking additional .where
clauses, etc, like this:
@users = filtered_users.joins(:posts).where('posts.created_at > ?', 1.week.ago)