I am using Ruby on Rails 3 and I would like to update an ActiveRecord avoiding the attr_accessible setting but returning a boolean value from the updating method. I know that, in order to avoid the attr_accessible setting, I can use this
@user.send :attributes=, @attrib, false
but that doesn’t return a boolean value.
I need that because I must handle updating success (when the update method returns true) or fault (when the update method returns false) behaviour in someway like this:
In the model:
class User < ActiveRecord::Base
attr_accessible #none
# or
# attr_protected :name, :surname
end
In the controller:
class UsersController < ApplicationController
# The following is the behaviour that I would like to handle (it is just an example: it is wrong and doesn't work)
if @user.send(:attributes=, { :name => params[:name], :surname => params[:surname] }, false)
...
else
...
end
end
Is it possible? If so, how? If no, there is another way to do that?
P.S.: In order to avoid AJAX injections, for me it is important to update only a limited number of attributes and do not update the @user ActiveRecord (see code in the example above) at all (maybe I don’t must use some method like a “global” save).
The proper method to bypass mass-assignment protected attributes is to use assign_attributes (only available in Rails 3.1+).
See http://apidock.com/rails/ActiveRecord/Base/assign_attributes
Here’s an example: