Provides tools to securely manage mass assignment in Rails models.
- Working with models:
# everything inside the block will honor attr_accessible
User.with_attr_accessible(:name, :email) do
u = User.new(:name => 'John', :email => 'johny@johnyland.com', :password => 'mypass')
# password was not initialized
puts "Password assignment protected?: #{u.password.nil?}"
end
# outside the block, attr_accessible is no longer used
u = User.new(:name => 'John', :email => 'johny@johnyland.com', :password => 'mypass')
# password was initialized
puts "Password assignment protected?: #{u.password.nil?}"
This will set name
and email
as the only accessible attributes of the class User, for the duration of the block.
- Working in controllers
In the body of your controller
filter_params :allow => [:preview, {:user => [:email, :name]}, {:project => [:name]}], :only => :update
This will filter parameters for action update
, leaving only :preview
, :user
and :project
keys. If under the :user
key of the parameters Hash
, another Hash
is found, its keys will be filtered leaving just :email
and :name
, same thing
will happend with :project
key. The structure of the :allow
parameter, is similar to the :include key in ActiveRecord::Base.find.
You could get a similar effect, but filtering inside the action, doing:
def update
filter_parameters_map(params, [:preview, {:user => [:email, :name]}, {:project => [:name]}])
...
end
Copyright © 2008 Sebastián Galkin, released under the MIT license