#008 Mass Assignment

| 18 minutes | security
介绍在使用Mass assignment时需要注意的一些安全问题。

Note: 视频中口误把Safari说成Firefox了,特此更正。 :p

黑名单方式:

app/models/user.rb
  attr_protected :admin

白名单方式:

app/models/user.rb
  attr_accessible :nickname, :email

对所有model强制使用白名单:

config/application.rb
  config.active_record.whitelist_attributes = true

在controller中处理Mass Assignment:

app/controllers/users_controller.rb
class UsersController < ApplicationController

  def show
    @user = User.find(params[:id])
  end

  def edit
    @user = User.find(params[:id])
  end

  def update
    @user = User.find(params[:id])
    if @user.update_attributes(user_params)
      flash[:notice] = "Update successfully."
      redirect_to @user
    else
      render :edit
    end
  end

  private
  def user_params
    params[:user].slice(:nickname, :email)
  end
end

相关资料参考:

Ruby China中的讨论
Proposal for Improving Mass Assignment
Mass assignment security shouldn't happen in the model
DHH's gist

Similar Episodes