2011-02-11 28 views
1

我有兩個型號:軌慘慘 - 定義權限嵌套模型

Thread (id, title) 
ThreadParticipation (id, thread_id, user_id) 

我想定義是這樣的:

can :create, ThreadParticipation if the user is a ThreadParticipation 

例如:

for 
    thread: (1, 'hello world') 
    thread_participation: (313, 1, 13) -- where 13 is the user_id 

我試着:

can :create, ThreadParticipation, :thread_participations => { :user_id => current_user.id } 

但那個錯誤。有任何想法嗎?

+1

的財產是它一個非常非常非常非常非常嚴重的錯誤? :D如果沒有一些錯誤信息,很難診斷! – Zabba

回答

0

我目前正在嘗試實現類似的事情,但我並沒有完全瞭解這一點。試試這個:

can :create, ThreadParticipation => Thread, do |participation, thread| 
    # your definition here 
end 

這也應該沒有阻止。

編輯:放下上面的部分,這還沒有在CanCan中工作。我實現了我自己的解決方案,但它需要您手動授權控制器操作,這不像美化,但在我看來更安全。

我實現這種方式爲我的項目: https://gist.github.com/822208

+0

謝謝,但我很困惑。 CanCan支持或不支持?我真的希望CanCan解決方案不會增加複雜性... – AnApprentice

+0

CanCan目前不支持嵌套資源(IMO)。主要解決方案是一個CanCan解決方案,再看一遍。我只是不使用可以嗎? ...在我的意見,但user_ability.can?因爲可以嗎?你只能接受一個參數(current_user或其他)。如果你自己創造一個能力,你可以定義更多的(比如在我的例子中,用戶和公司),並且可以在這個上面工作。 – pduersteler

1

Thread一般僅僅是一個壞榜樣的名字,因爲它會與在Ruby中定義的Thread類衝突。我剛剛實施了這個。在我的例子中,我有論壇和主題。一個人不應該能夠在他們沒有閱讀權限的論壇中創建一個新話題。

我的論壇對象上定義自定義權限呼籲該create_topic

can :create_topic, Forem::Forum do |forum| 
    can?(:read, forum) && user.can_create_forem_topics?(forum) 
end 

can_create_forem_topics?只是在User模型是這樣定義的:

def can_create_forem_topics?(forum) 
    # code goes here 
end 

然後,我只是用這個自定義:create_topic在我的TopicsController中的newcreate操作中的能力,其中@forumbefore_filter

authorize! :create_topic, @forum 

如果我需要使用它的觀點:由父對象上定義自定義權限

can? :create_topic, @forum 

0

通常你會用戶

user 

不是 current_user

within ability.rb。這是你的錯誤嗎?以及你的能力被錯誤地指定。你想

can :create, ThreadParticipation, :user_id => user.id 

注意:USER_ID是ThreadParticipation模型