Riding Rails: Strong parameters: Dealing with mass assignment in the controller instead of the model
Rails4のMass Assignment対策としてStrong parametersを利用するとのこと。(既にgem化されている)
google readerが新しいfeedを取ってきてくれてないので
全然気づいてませんでした。
(padrino使ってたら、activesupport3.2.3が入って驚いた)
Strong parameters
parameterをsliceして使うこともあるから
model側でなくcontroll側で制御する。
sampleが分かりやすいんだけど、
person_paramsなかで許可するパラメータを設定している。
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.require(:person).permit(:name, :age) end end
More work to be done
nested parametersの実装がまだなのと、
Yehudaさんが標準的なformの場合、自動的に設定するような仕組みを作ろうとしてくれてるっぽい。