Prev | Current Page 194 | Next

Brad Ediger

"Advanced Rails"

new params[:person]
The params[:person] object is a hash mapping attribute names to values, translated
from the form parameters courtesy of ActionController:
{:first_name => "John", :last_name => "Smith", :email => "john@example.com"}
Those parameters are assigned to the Person object, calling the Person#first_name=,
Person#last_name=, and Person#email= setters, respectively. It is just as if we had set
them individually:
person = Person.new
person.first_name = params[:person][:first_name]
person.last_name = params[:person][:last_name]
person.email = params[:person][:email]
This is a handy shortcut, but it leaves us vulnerable. Suppose someone submits the
form with a field named person[access_level]. Remember, the values that they submit
need have no relation to the form we send them. By default, this would call
Person#access_level= with the value provided in the form. Clearly, we need to protect
against this. We can either use the attr_protected or attr_accessible class
methods of ActiveRecord::Base. The attr_protected method specifies which
attributes may not be assigned to via mass assignment:
class Person < ActiveRecord::Base
attr_protected :access_level
end
Conversely, the attr_accessible method specifies which attributes may be assigned
to with mass assignment; any attributes not on the list are blocked. This is preferable
when the list of attributes may change, as it represents a ???default deny??? stance.


Pages:
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206