Reputation: 915
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?
Upvotes: 0
Views: 967
Reputation: 5553
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.
Upvotes: 0
Reputation: 131112
Perhaps:
Employee.all(:joins => :bosses, :conditions => {:superior_id => User.current_user.employee})
Upvotes: 2