Friday, May 4, 2007

Safe model attribute updates using AJAX

Sometimes it is nice to have little AJAX click to edit controls that update specific attributes in a model. There are many ways to implement this functionality, some more DRY than others. The code below references an example application that contains users with a corresponding User model. Once authenticated, the user object is stashed in the session. In the following code, current_user references the instance of User for the currently authenticated user. One might be tempted to do the following in the corresponding controller:

def method_missing(name)
match = /\Aupdate_([a-z]{1,20})\Z/.match(name.id2name)
if match && current_user && current_user.attributes.keys.include?(match[1])
if params[:value]
current_user.update_attribute(match[1],params[:value])
current_user.reload
render :text => current_user.send(match[1])
else
render :nothing => true, :status => 500
end
else
raise NoMethodError, "undefined method '#{name}'"
end
end

This is a good time to point out that care must be taken with the choice of attributes=, update_attribute or update_attributes. attributes= is a good choice, because it pays attention to protect attributes that have been excluded from mass-assignment. Using attr_protected or attr_accessible gives one a consistent mechanism to protect sensitive attributes, which one might assume a user object has. attributes= requires an explicit save call on the object afterwards. update_attribute is probably never a good choice, since it bypasses validations. update_attributes actually just calls attributes= and does the save in one call, so it conforms to the protections provided by attr_protected and attr_accessible. update_attributes is probably the best choice here.

The best solution is to use the attr_protected or attr_accessible mechanisms in your model to restrict sensitive attributes from mass assignment. Since the following reference code uses update_attributes, your attribute restrictions will apply to this update mechanism:

def method_missing(name)
match = /\Aupdate_([a-z]{1,20})\Z/.match(name.id2name)
if match && current_user && current_user.attributes.keys.include?(match[1])
if params[:value]
current_user.update_attributes(match[1] => params[:value])
current_user.reload
render :text => current_user.send(match[1])
else
render :nothing => true, :status => 500
end
else
raise NoMethodError, "undefined method '#{name}'"
end
end

This code is simplified, since the object we need to reference is readily available in the session hash. If you need to pass an object id, you would need to extend the AJAX call (using the :with option for the JavaScriptMacrosHelpers) to include the id as an additional parameter and retrieve the object in the normal way.

Notice this code uses update_attributes and constructs a hash of the attribute name and the value.

In the view, you would have erb such as:

Name: <p id="user_name"><%= h @current_user.name %></p>
<%= in_place_editor 'user_name', {:url => '/user/update_name' } %>

If you feel you need to deviate from the normal attribute protection scheme (you should not as a general principle), then you can do something like this in your model:

def self.protected_attributes
['id','type','salt','hashed_password','verify_code']
end

def safe_attribute?(attr_name)
(self.attributes.keys - User.protected_attributes).include? attr_name
end

and then add it to your method_missing hook like:

def method_missing(name)
match = /\Aupdate_([a-z]{1,20})\Z/.match(name.id2name)
if match&& current_user && current_user.safe_attribute?(match[1])
if params[:value]
current_user.update_attributes(match[1] => params[:value])
current_user.reload
render :text => current_user.send(match[1])
else
render :nothing => true, :status => 500
end
else
raise NoMethodError, "undefined method '#{name}'"
end
end

Hooking method_missing is a little dirty. You might actually need to hook method_missing for other (better) reasons. Here is a solution that is dirty in a different way. In the controller:

private

def called_as
/`([^']*)'/.match(caller[0])[1]
end

public

def update_attr_generic
match = /\Aupdate_([a-z]{1,20})\Z/.match(called_as)
if match && current_user && current_user.attributes.keys.include?(match[1])
if params[:value]
current_user.update_attributes(match[1] => params[:value])
current_user.reload
render :text => current_user.send(match[1])
else
render :nothing => true, :status => 500
end
else
render :nothing => true, :status => 500
end
end

alias_method(update_name, update_attr_generic)
alias_method(update_phone, update_attr_generic)

The obvious down side being that you have to create an aliased method name for each attribute you want the ability to update (code generation?). I am jumping through this naming hoop because, by default, the AJAX stuff included in rails likes to post a single parameter (:value) to a named action (commonly :controller/:action). If you modify the AJAX call to send the attribute name and value, or have a more complicated route map and URI, then you can ditch the method name introspection, regular expression and alias_method foolishness and have a single update_attr method. For example (replace ObjModelClass with the model name):

def update_attr
obj = ObjModelClass.find(params[:id])
if obj && obj.attributes.keys.include?(params[:attrname])
if params[:value]
obj.update_attributes(params[:attrname] => params[:value])
render :text => obj.send(params[:attrname])
else
render :nothing => true, :status => 500
end
else
render :nothing => true, :status => 500
end
end

There you go! A generic attribute updater for a given AR model that adheres to attribute protections placed with attr_protected or attr_accessible. However, you will have to do a little more work in your views to make the AJAX methods pass :id, :attrname and :value parameters to the action. I like to simplify my views, so I often use the dirty, lazy method_missing implementation previously described.

BTW, these methods respond with the value of the attribute after the update, successful or not. If no value is passed in the parameters, the response is an HTTP error code, which most Javascript AJAX libraries handle OK.

Another quick point is that this is pretty generic functionality. All the attribute validation and restrictions should be in your models. Models are the object-oriented part of the RoR MVC implementation. Controllers are the procedural part of your application. Keep your controller code simple. If you find yourself duplicating code in controller actions, it probably can be put into a model (one place to fix and DRY). By using update_attributes or attributes=, you leave the security and enforcement in the model where it belongs.

Go ahead, pick your poison.

No comments: