views:

209

answers:

2

I've got a table with employees (id, name, role) and a relations table bosses (employee_id, superior_id; both foreign_keys to employees.id to employees).

Now if a employee logs in, I only want to show his/her employees; an admin (role=admin) can see all employees.

For the admin it's easy:

Employee.find(:all) #to list them
Employee.find(params[:id] #to find one

Is there an easy way to limit the results on just my employees?

Like add always a condition

where employees.id in
 (select id from bosses where superior_id = #{User.current_user.employee})

if role is not admin.

Additional Comment

Could you think of a more general solution, where every time a call the find method in active record, it checks for the current_user and returns only the elements, he/she should see?

+2  A: 

Perhaps:

Employee.all(:joins => :bosses, :conditions => {:superior_id => User.current_user.employee})
Sam Saffron
yes, this solves it, at least once, but actually I'm still looking for a more general solution. Like every time I call a find, it limits the user on the people, he/she has access to.
Beffa
named scopes perhaps, http://railscasts.com/episodes/108-named-scope
Sam Saffron
You showed me the right path. I used the code from the named scope, to write a scoping for myself
Beffa
A: 

You can do something like

@boss = Boss.find(params[:id], :include => [:employees])

To fetch a boss and their employees. Then use

@boss.employees

to get that boss's employees.

Eifion