代码之家  ›  专栏  ›  技术社区  ›  daniel

DRY me:Rails代码

  •  1
  • daniel  · 技术社区  · 14 年前

    我怎么能把这个擦干?

    def correct_user
      @company = RealEstateCompany.find(params[:id])     
      if(current_user != @company.user)
        redirect_to(root_path)
      end
    end  
    
    def correct_user
     @company = ConstructionCompany.find(params[:id])     
     if(current_user != @company.user)
       redirect_to(root_path)
     end
    end
    

    def correct_user_for_controller?(controller_name)
      @company = controller_name.classify.constantize.find(params[:id])     
      redirect_to(root_path) unless (current_user == @company.user)
    end     
    

    然后在任何控制器内部包括模型和使用

    correct_user_for_controller?("ConstructionCompany") 
    
    correct_user_for_controller?("RealEstateCompany")
    
    3 回复  |  直到 14 年前
        1
  •  1
  •   Harish Shetty    14 年前

    假设你想把这个设施放在里面 ConstructionCompaniesController RealEstateCompaniesController

    def correct_user
      @company = controller_name.classify.constantize.find(params[:id])     
      redirect_to(root_path) unless (current_user == @company.user)
    end 
    
        2
  •  3
  •   glebm    14 年前
    module OwnershipPermission
        def accessible_for_user?(user)
            self.user == user
        end
    end
    

    只需将此模块包含在两个模型中并执行模型级别检查。 您也可以为控制器创建一个模块,但我强烈建议不要这样做(损害可维护性)。

        3
  •  2
  •   Community CDub    8 年前

    看起来您正在尝试进行授权检查(<clippy>)。

    这个 thread on authorization for rails 举几个例子。尤其是 CanCan

    authorize! :read, @company
    

    上面写着“当前用户是否有权查看@company的详细信息”。