views:

26

answers:

1

Hi,

i have 3 models

users, companies and roles

User belongs_to role User has and belong to many companies Role has_one User

Thru this association i can do something like:
User.companies <-- i get all companies that a user has
User.role <-- i get the role that a user belongs_to

I was thinking now, when a user has role_id == 0 (admin) the companies should return all companies (Company.all). To do it i was thinking to overwrite the companies method and if a user has role_id == 0, i return Company.all otherwise i call super. Is that correct? if yes, how should i implement this code? Directly in my User Model? Should i just extend Array?

+1  A: 

I'd say make a new method, companies_accessible, that determines to what companies a user has access.

def companies_accessible
  role_id == 0 ? Company.all : companies
end

No need to pollute your existing methods, especially if you later need to determine what companies an admin really does own.

Matchu
it works, but then i will have to change a lot of code that it ready already.
VP
It's probably worth it for sane code, and probably not much more than an across-project find-and-replace (checking all replaces manually, of course). If you use an IDE, it probably has it. If not, there are command-line tools that can do this for you.
Matchu
i won't take this approach. i will override the companies and pray. anyway, you answered alone, so i will choose your answer.
VP
Mmkaaay... that's technically not what the `companies` method represents, but whatever works. If you're using this for authorization purposes, you may want to look into an actual authorization system in the future, such as CanCan: http://github.com/ryanb/cancan
Matchu
i'm using declarative authorization that is pretty good http://github.com/stffn/declarative_authorization.
VP