rails 应该在那一层过滤非法 request 参数,怎么过滤?
比如模型 Order 有个 price 的属性,该属性不允许用户私自更改,在 controller 层调用 @order.update_attributes(params[:order]),如果用户传入非法参数 price,如果执行检验或过滤。
rails 应该在那一层过滤非法 request 参数,怎么过滤?
比如模型 Order 有个 price 的属性,该属性不允许用户私自更改,在 controller 层调用 @order.update_attributes(params[:order]),如果用户传入非法参数 price,如果执行检验或过滤。
[quote]我这里的非法参数是指不应该被保存到模型对象的参数,而当调用 @order.update_attributes(params[:order])所有参数都将被保存。
如何过滤或验证这些参数比较优雅? [/quote]
rails有这样一个方法。
attr_protected(*attributes)
可以看下api,或者google下都可以找到答案的。
我吧api的代码贴出来,希望对你有帮助。
[code="ruby"] class Customer < ActiveRecord::Base
attr_protected :credit_rating
end
customer = Customer.new("name" => David, "credit_rating" => "Excellent")
customer.credit_rating # => nil
customer.attributes = { "description" => "Jolly fellow", "credit_rating" => "Superb" }
customer.credit_rating # => nil
customer.credit_rating = "Average"
customer.credit_rating # => "Average"[/code]