Rails application with 500 models
I have a Rails application in which I have hundreds of models that only have CRUD operations. I could use scaffold / active scaffold, but then I had so many files in my app directory.
Is it possible to do something like have a common model, view and controller to handle them, and not have 500 of them in the application folder.
source to share
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 method current_model
will create a child ActiveRecord::Base
on the fly. Of course, this code is very simple.
Update: This will complain about the lack of a method constantize=
. You'll probably have to do something like this: Kernel.const_set(params[:model], Class.new(ActiveRecord::Base))
.
source to share
I will describe what August said. There is also a bug. It should be:
def current_model
params[:model].constantize
end
You probably want to filter out the model it might be, otherwise it might get messy if you have any private models that they shouldn't have access to.
For presentation, you can check how many columns the model has and prepare appropriate fields for them.
source to share
Another option is to use a plugin that creates rich CRUD interfaces. ActiveScaffold is a good example . Creating an interface is as easy as:
class UsersController < ApplicationController
active_scaffold :user
end
source to share