关于Rails 4 strong parameter 初步理解

         Rails 4废除了之前的attr_accessible机制,为了安全起见,使用了新的strong parameter。写代码遇到点小问题,简单了解一下。官方教程      http://edgeguides.rubyonrails.org/action_controller_overview.html#strong-parameters

   

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::ParameterMissing exception, which will get
  # caught by ActionController::Base and turned into that 400 Bad
  # Request reply.
  def update
    person = current_account.people.find(params[:id])
    person.update_attributes!(person_params)
    redirect_to person
  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

           这段代码是教程中的例子,看内容不难理解的是,类定义了一个私有方法来决定哪些参数可以被允许,不在白名单中的参数都将被过滤掉。

 

           关于

               Permitted Scalar Values

                     对于如下代码:

params.permit(:id)

                      如果其中的:id 对应的参数在白名单中,定义scalar方法如下:

params.permit(id: [])

                      其中列表中的键就是被允许的键,如果想讲所有id都列入白名单,则:

params.require(:log_entry).permit!

                      这样的话log_entry 所有子键都讲被允许。

 

 

 

posted @ 2013-07-12 16:08  孤独的小马哥  阅读(1528)  评论(0)    收藏  举报