2015-01-20 67 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