Rails 关于不同用户有不同的字段验证,该采用什么样的策略?

bydmm · 2013年06月03日 · 最后由 feipinghuang 回复于 2013年06月03日 · 2794 次阅读

第一个问题: 现在项目已经使用了 CANCAN 这个 GEM,但是 CANCAN 没有解决不同用户的字段验证的问题。

现在有 4 个等级的用户,比如是 admin,manger,editor,student,guest,这个存在用户表的 role 字段内。

上层的用户可以给下层的用户提权, 比如 manger 可以把 guest 用户提权到 editor,但是 manger 不能把用户提到 admin 这个级别。

实际上这就是一个根据不同的用户进行字段验证的一个问题。

问题是,这一块我们只能将验证的代码分散到 model 的 validate 内,这样就不怎么 CANCAN 了,你们是怎么解决的。

第二个问题: 现实项目中,我们使用的 devise,由于 devise 的 current_user 不能在 model 里使用。 这又带来了一个问题。

我们每次都使用了一个较为复杂的路径,将某个用户在某个字段允许的数组传进去。

#models/License.rb
class License < ActiveRecord::Base
  attr_accessible  :role

  validate :validate_roles

  def roles= (new_roles)
    @roles = new_roles
  end

  def validate_roles
    if !@roles.include? role
      errors.add(:role, "#{role} is not a valid roles")
    end
  end

end
#controllers/licenses_controller.rb
class LicensesController < ApplicationController

  def create
    @license = License.new(params[:license])
    @license.roles = roles
    respond_to do |format|
      if @license.save
        format.html { redirect_to @license, notice: 'License was successfully created.' }
        format.json { render json: @license, status: :created, location: @license }
      else
        format.html { render action: "new" }
        format.json { render json: @license.errors, status: :unprocessable_entity }
      end
    end
  end

  def roles
    case current_user.license.role
        when "admin"
            super_roles
        when "manager"
            return %w[committee teacher student]
        when "committee"
            return %w[teacher student]
        when "teacher"
            return %w[student]
    end     
  end

end

如上面的代码所示,在 create 的时候,根据 current_user 的 role 产生了一个数组,然后传进 model 的 validate 内进行判断。

于是第二个问题是,devise 在 model 内有办法调用到 current_user 这个方法么

需要 登录 后方可回复, 如果你还没有账号请 注册新账号