2017-05-12 54 views
1

我已經宣佈在cancancan寶石作用的能力(導軌5,Postgres的,設計):cancancan行篩選

can [:update, :show, :destroy, :index], SalesDatum do |datum| 
    datum.try(:user_id) == user.id #the ids just access the id's from the user object that is passed into can can and from the table 
end 

SalesDatumuser_id場。

這部作品演出的行動,因爲我已經登錄的user_idshow的SalesDatum例如:

http://localhost:8080/projects/19/sales_data/961 正確通過驗證,因爲登錄USER_ID user_ID的匹配上SALES_DATA

http://localhost:8080/projects/19/sales_data/800 正確沒有得到驗證,因爲登錄的USER_ID不會對SALES_DATA

然而user_ID的匹配,當我去到GE t指數操作: http://localhost:8080/projects/19/sales_data 它顯示@sales_data變量的所有銷售數據。因此,它會顯示在data.id 800和961

銷售數據控制器:

load_and_authorize_resource 
def index 
    @sales_data = SalesDatum.where(project_id:params[:project_id]) 
end 

如何獲得索引操作僅與相關USER_ID顯示數據?根據user_id,康康不應該過濾嗎?

+0

我可以編輯控制器查詢到'SalesDatum.where(project_id:params [:project_id]),其中(user_id:'current_user.id')',但這似乎是一種非常糟糕的身份驗證方式? – HoosierCoder

+0

這就是爲什麼我放棄了CanCanCan而贊成Pundit--這個看似簡單的DSL在定義認證範圍或處理任何不平凡的事情方面做得並不好。 – max

回答

1

您需要使用哈希語法定義規則。

can [:update, :show, :destroy, :index], SalesDatum, user_id: user.id 

還可能要定義的edit動作,因此:

can [:edit, :update, :show, :destroy, :index], SalesDatum, user_id: user.id 

這可以簡化爲:

can :manage, SalesDatum, user_id: user.id 

如果SalesDatum具有belongs_to :user定義也可以寫成:

can :manage, SalesDatum, user: user 
+0

這真是太棒了,難道沒有一個好的方法可以用塊語法來做到這一點嗎? – HoosierCoder

+1

塊語法應始終是最後一個選擇,因爲它僅適用於實例而不適用於集合。對於您需要使用散列語法的集合。 – coorasse