This might not be the cleanest rest technique, but it will replace 4 controllers with 1 and gain DRY leverage. In my application I have 4 models that have the same validations, attributes and consequently all of those models have their own restful controllers. The code in the controllers are more or less identical except for the model name which is Color, Brand, Category or Size. Here is how I created a single controller to handle all of these models restfully.
I added a parameter[:type] to each request which contains “color”, “brand”, “category” or “size”. From that string, all I have to do is to go from here:
@color = Color.find(params[:id])
to
@model = model_name.find(params[:id])
To do that I defined
before_filter :find_class
attr_accessor :model_name, :type
def find_class
self.type = params[:type]
self.model_name = params[:type].camelize.constantize
end
This will take the param[:type], which is a lowercase string initially, camel-case it, and turn it into an ActiveRecord constant you can use for database queries. 4 controllers in one.
« Back to posts Write a new comment