根据模型属性禁用路由

时间:2015-01-20 19:43:58

标签: ruby-on-rails rails-routing

考虑到我有Project模型,必须批准项目可编辑,无法编辑status=pending的项目。

我曾经这样做是基于状态属性隐藏视图上的编辑链接,但这并不能阻止用户通过浏览器输入路径(例如:projects/1/edit),怎么能我让编辑路线在给定的项目状态下无法访问?

2 个答案:

答案 0 :(得分: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 :(得分: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