views:

168

answers:

4

I have a Rails App in which I have hundreds of model that only have CRUD operations. I could use scaffold/active scaffold but then I end up having so many files in my application directory.

Is it possible to do something like have a generic model, view and controller to handle these rather than having 500 of them in the application folder.

+6  A: 

Sure.

class GenericCrudController < ApplicationController
  def index
    current_model.find(:all)
  end

  private

  def current_model
    params[:model].constantize = Class.new(ActiveRecord::Base)
  end
end

The current_model method will create a descendant of ActiveRecord::Base on the fly. This code is very basic, of course.

Update: This will complain that there is no constantize= method. You probably have to do something like this instead: Kernel.const_set(params[:model], Class.new(ActiveRecord::Base)).

August Lilleaas
+1  A: 

I'll build on what August said. There is also a mistake. It should be:

  def current_model
    params[:model].constantize
  end

You will probably want to filter what the model can be, else it could get messy if you have any private models that they shouldn't have access to.

For the view, you can check to see how many columns the model has and prepare the appropriate fields for them.

Jim
A: 

Another option is to use a plugin which makes rich CRUD interfaces. A good example is ActiveScaffold. Creating the interface is as easy as:

class UsersController < ApplicationController
  active_scaffold :user
end
Edwin V.
I've tried active scaffold and it seems good but the problem is I still end up having 500 files in the directory which I don't want.
Sunny
Yeah, that's correct. Maybe you can combine the current_model approach from August and Jim with active_scaffold.
Edwin V.
+1  A: 

Slightly off-topic but I'm intrigued, 500 models is no small number. What's the app?

fractious