Forum: Ruby on Rails Data from DB based on role

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
969047aea93d01a9cc636e9867f4ec0f?d=identicon&s=25 Serafino Picozzi (serpico)
on 2009-03-26 14:19
I'm creating a rails app requiring an ACL system to grant different
priviledges to users, but I have some doubts on how to structure it.

Right now I have three users: Administrator > Area manager > Employee

I'm able to distinguish between users and block certain actions or
controllers based on the role. What I don't get is how to manage in a
clean way situations where different kind of users access the same
action, but have to display and get different data from the database.

Example:

An employee has_many :documents , and in the index action of the
documents_controller I have to get HIS documents (something like
current_user.documents), but an area manager accessing the same action
has to get ALL the documents (Document.find(:all))

I can't think of a clean way to implement this avoiding conditions in
the controller like "if the user is a X, find(something) else
find(something else)"

Thanks in adavance for your suggestions
D188e591eac11021329b8821a5f954c7?d=identicon&s=25 Ar Chron (railsdog)
on 2009-03-26 15:30
You'll have to scope the find at some point, and if this requirement is
really pervasive, I'd recommend creating a find_using_role_or_id method
(or something like that) which at least lets you write and maintain that
"find scoping" code in a single place, not in every controller's index
method.

Patch it in to ActiveRecord, or create an abstract class that sits
between ActiveRecord and the rest of your models and implements the
method.
969047aea93d01a9cc636e9867f4ec0f?d=identicon&s=25 Serafino Picozzi (serpico)
on 2009-03-26 15:35
Ar Chron wrote:
> You'll have to scope the find at some point, and if this requirement is
> really pervasive, I'd recommend creating a find_using_role_or_id method
> (or something like that) which at least lets you write and maintain that
> "find scoping" code in a single place, not in every controller's index
> method.
>
> Patch it in to ActiveRecord, or create an abstract class that sits
> between ActiveRecord and the rest of your models and implements the
> method.

Thanks for your reply. It's a good suggestion, but in fact the scope is
not limited to the find, sometimes I have to perform some code in the
controller not related to AR but different from user to user.

In the past in thos situations I used to create a different namespace
for every user, with shared views, but this has the disadvantage to have
a lot of controllers which are really similar
This topic is locked and can not be replied to.