2015-01-20 64 views
0

考慮到我有Project模型,項目必須被批准爲可編輯項目,但不能編輯status=pending的項目。基於模型屬性禁用路線

我以前通過在視圖上隱藏基於狀態屬性的編輯鏈接來做到這一點,但這並不能阻止用戶通過瀏覽器進入路由(例如:projects/1/edit),我該如何編輯路由在給定項目狀態下無法訪問?

回答

2

您不想製作條件路線。讓控制器檢查狀態並只允許更新如果status =='pending'

def edit 
    @project = Project.find(params[:id]) 
    if @project.status == 'pending' 
    render :head, :status=>401 
    else 
    #your edit code 
    end 
end 
1

請在下面添加before_action,以防止項目被編輯。

#projects_controller.rb 
before_action :can_edit?, only: :edit 

def edit 
    #your existing implementation goes here. 
end 

def can_edit? 
    @project = Project.where(id: params[:id]).first 

    if @project.status == pending 
    flash[alert] = "Sorry can't be edited" 
    redirect_to projects_path 
    end 
end