强参数 Strong parameters: Dealing with mass assignment in the controller instead of the model

We're exploring a new way to deal with mass-assignment protection in Rails. Or actually, it's not really a new way, it's more of an extraction of established practice with some vinegar mixed in for when you forget. This new approach is going to be a part of Rails 4.0 by default, but we'd like your help in testing and forming it well in advance of that release.

Strong parameters

This new approach is an extraction of the slice pattern and we're calling the plugin for it strong_parameters (already available as a gem as well). The basic idea is to move mass-assignment protection out of the model and into the controller where it belongs.

The whole point of the controller is to control the flow between user and application, including authentication, authorization, and as part of that access control. We should never have put mass-assignment protection into the model, and many people stopped doing so long ago with a move to the slice pattern or a variation there of. It's time to extract that pattern and bring it to the people.

Example

class PeopleController < ActionController::Base
  # This will raise an ActiveModel::ForbiddenAttributes exception because it's using mass assignment
  # without an explicit permit step.
  def create
    Person.create(params[:person])
  end

  # This will pass with flying colors as long as there's a person key in the parameters, otherwise
  # it'll raise a ActionController::MissingParameter exception, which will get caught by 
  # ActionController::Base and turned into that 400 Bad Request reply.
  def update
    redirect_to current_account.people.find(params[:id]).tap do |person|
      person.update_attributes!(person_params)
    end
  end

  private
    # Using a private method to encapsulate the permissible parameters is just a good pattern
    # since you'll be able to reuse the same permit list between create and update. Also, you
    # can specialize this method with per-user checking of permissible attributes.
    def person_params
      params.required(:person).permit(:name, :age)
    end
end

转自:http://weblog.rubyonrails.org/2012/3/21/strong-parameters/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值