class Users < ApplicationController
def create
@user = User.create params[:user]
end
end
这类方法是我们常用的表单到模型的附值了。
也是经常出现漏洞的地方。具体有哪些漏洞就不说,网上有很多介绍。
通常我们为了解决这个问题都在Model中用attr_protected
或 attr_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