Being a newbie ROR developer I’ve been thinking of ways of protecting certain methods to make sure the correct user is updating their own content. Here is an example of my approach.
Would you recommend a cleaner way or better way of doing such tasks?
# Example Controller
class Owner::PropertiesController < Owner::BaseController
def index
end
etc.....
def update
@property = Property.find(params[:id])
# Check correct owner
check_owner(:owner_id => @property.owner_id)
if @property.update_attributes(params[:property])
redirect_to([:owner, @property], :notice => 'Property was successfully updated.')
else
render :action => "edit"
end
end
def destroy
@property = Property.find(params[:id])
# Check correct owner
check_owner(:owner_id => @property.owner_id)
@property.destroy
redirect_to(owner_properties_url)
end
private
def check_owner p = {}
if p[:owner_id] != session[:owner_id]
redirect_to([:owner, @property], :notice => "Property not found.")
end
end
You could use a gem like declarative_authorization to do this as well. If you want to do it yourself I would recommend simply DRYing up your code a little bit:
Additionally, you can filter your properties by an owner to ensure that a user who is not the owner can not interact with properties that aren’t his/hers. For example:
This forces the properties that you are searching to be the ones that belong to the session[:owner_id] instead of the entire universe of properties. This means that properties that the session[:owner_id] does not own will not even be considered. You can then put this code into a before_filter as well so that it’s reusable in multiple actions.