簡體   English   中英

限制活動記錄查找的結果

[英]Limit the results of a active record find

我有一個包含雇員(id,名稱,角色)的表和一個關系表老板(employee_id,superior_id;這兩個都是對employees.foreign_keys的雇員)。

現在,如果一個員工登錄,我只想顯示他/她的員工; 管理員(role = admin)可以看到所有員工。

對於管理員來說很簡單:

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

有沒有一種簡單的方法可以將結果限制在我的員工身上?

就像總是添加一個條件

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

如果角色不是管理員。

附加評論

您能想到一個更通用的解決方案嗎?每次在活動記錄中調用find方法時,它都會檢查current_user並僅返回他/她應該看到的元素?

也許:

Employee.all(:joins => :bosses, :conditions => {:superior_id => User.current_user.employee})

你可以做類似的事情

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

為了獲取老板及其雇員。 然后使用

@boss.employees

找那個老板的員工

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM