before_filter :find_this
before_filter :find_that
def find_this
def find_that
When your application grows and starts having something like a dozen models, plus you might have nested routes where you need to check the security against the nested elements too, those things tend to get really messy.
So here is a simple method which I use on my projects
before_filter :find_restful_units
def find_restful_units
params.each do |key, value|
if key == 'id' || key.ends_with?('_id')
unit_name = key == 'id' ? controller_name.singularize : key.gsub('_id', '')
unit_class = Object.const_get(unit_name.camelize)
instance_variable_set("@#{unit_name}", unit_class.find(params[key]))
end
end
rescue NameError # just hung up if there is no such unit
nil
end
You put this in your ApplicationController and it will automatically find and assign all your models, the actual and the nested ones.
This makes controllers much cleaner and you always have your models extracted and ready to use in the standard way.
No comments:
Post a Comment