before_filter,带参数来验证用户的权限

go *_*mal 2 ruby-on-rails

在允许用户编辑员工信息之前,我需要确保用户具有正确的权限.具体而言,用户必须是管理员,并且用户必须与员工属于同一公司.做这样的事情最好的方法是什么?

def EmployeesController < ApplicationController
  before_filter :requires_admin_from_company(cid)

  # Only allow access to this if user.admin is true and user.company_id is equal to employee.company_id
  def update
    # Somehow pass @employee.company_id into admin
    @employee = Employee.find(params[:id])
    @employee.update_attributes(params[:employee])
  end

  def requires_admin_from_company(cid)
    if !@current_user.admin? || @current_user.company_id != cid
      redirect_to login_url
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

mon*_*cle 5

怎么样

before_filter lambda{ requires_admin_from_company(params[:cid]) }, :only => :create
Run Code Online (Sandbox Code Playgroud)