另類附值指定參數的方法(不用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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章