另类附值指定参数的方法(不用attr_accessible 或 attr_protected)

class Users < ApplicationController
    def create
      @user = User.create params[:user]
    end
end

 

这类方法是我们常用的表单到模型的附值了。

 

也是经常出现漏洞的地方。具体有哪些漏洞就不说,网上有很多介绍。

 

通常我们为了解决这个问题都在Model中用attr_protectedattr_accessible 来解决。

 

另外还可以通过精确挑选需要的值来进行操作。

 

class Users < ApplicationController
    def create
        @user = User.new
        @user.login = params[:user][:login]
        @user.password = params[:user][:password]
        @user.password_confirmation = params[:user][:password_confirmation]
        @user.save
        #user is 创建了, 但is_admin 权限没有附值
    end
end

 为了简化代码,我们只用到了下面五行解决

 

class Users < ApplicationController
    def create
      @user = User.create(
        params.split_off(:login, :password, :password_confirmation) )
    end
end

 

这是一DRY应用,split_off 在helper中

 

class Hash
    def split_off(*keys)
      h = {}
      keys.each { |key| h[key] = self[key] }
      h
    end

 

排除的版本 

 

   def split_off!(*keys)
      h = {}
      keys.each { |key| h[key] = delete key }
      h
   end
end

 

允许一个不同的action (和一个block) ,如果他们key中没有value:

 

class Hash
    def split_off(*keys)
      h = {}
      if block_given?
        keys.each do |key|
          val = self[key]
          h[key] = val.nil? ? yield(key) : val
        end
      else
        keys.each { |key| h[key] = self[key] }
      end
      h
    end

    def split_off!(*keys)
      h = {}
      if block_given?
        keys.each do |key|
          val = delete(key)
          h[key] = val.nil? ? yield(key) : val
        end
      else
        keys.each { |key| h[key] = delete(key) }
      end
      h
    end
end

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值