2012-04-27 129 views
0

我試圖添加一個按鈕來標記在Rails中讀取的答覆。我目前有這樣的事情。允許cancan Ability.rb只管理訪問模型的特定字段

# /app/models/ability.rb 
... 
can :manage, Reply, :user_id => user.id 
... 

我也load_and_authorize_resource在我RepliesController

# /app/controllers/replies_controller.rb 
class RepliesController < ApplicationController 
    load_and_authorize_resource 

    def update 
    @reply = Reply.find(params[:id]) 
    @reply.isRead = true 
    if @reply.save 
     flash[:notice] = "Marked as ready." 
     flash[:alert] = params[:id] 
     redirect_to root_path 
    else 
     render :action => 'new' 
    end 
    end 

我有一個按鈕,其中爲已讀用戶可以標記一個回覆。

= button_to "Mark as read", idea_reply_path(reply.idea,reply), :method => "put" 

問題是,因爲我想在ability.rb(頂部)定義更新來自其他user.id所有者的對象,我沒有權限對其進行編輯。

如果我添加這樣的東西它會工作,但我也賦予管理整個回覆對象給其他人的權利。

can :manage, Reply, :to_user_id => user.id 

我需要一種方法來只允許用戶管理對象,他是user.id匹配to_user_id的屬性isRead?

回答

3

您可以在控制器中定義一個新的動作像mark_as_read

def mark_as_read 
    #action to mark as read 
end 

,並在能力定義

can :manage, :Reply, :user_id => user.id 
can :mark_as_read, :to_user_id => user.id 

排序非常重要。現在,登錄用戶可以管理回覆,並且用戶是用戶,只有mark_as_read功能。

+0

我會建議爲mark_as_read添加不同的操作,而不是授予更新操作的權限。這樣Update操作可以用於修改回覆 – naren 2012-04-27 00:52:35

0

我認爲你可以同時擁有

can :manage, Reply, :user_id => user.id 
can :update, Reply, :to_user_id => user.id 

如果更新操作只對標記回覆爲,然後讀這就是你想要什麼