【问题标题】:Disable a route based on model attribute根据模型属性禁用路由
【发布时间】:2015-01-21 03:49:13
【问题描述】:

考虑到我有一个Project 模型,必须批准项目才能编辑,不能编辑status=pending 的项目。

我曾经通过根据状态属性在视图上隐藏编辑链接来做到这一点,但这并不能阻止用户通过浏览器输入路线(例如:projects/1/edit),我该如何进行编辑在给定的项目状态下无法访问路由?

【问题讨论】:

    标签: ruby-on-rails rails-routing


    【解决方案1】:

    您不想创建条件路由。让控制器检查状态并仅在 status =='pending' 时允许更新。

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

    【讨论】:

      【解决方案2】:

      请在下面添加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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-01-17
        • 2016-01-23
        • 1970-01-01
        • 2013-10-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-15
        相关资源
        最近更新 更多