0

I have an STI model that has over 20 subclasses and I need to point them all to the parent controller in my routes. I have been defining each one in the routes, but this is really inefficient and not DRY. This is how it looks now.

  resources :red_master_models, :controller => 'master_models'
  resources :green_master_models, :controller => 'master_models'
  resources :yellow_master_models, :controller => 'master_models'
  resources :purple_master_models, :controller => 'master_models'
  resources :orange_master_models, :controller => 'master_models'
  resources :grey_master_models, :controller => 'master_models'
  resources :indigo_master_models, :controller => 'master_models'
  resources :blue_master_models, :controller => 'master_models'

I feel like I should be able to loop all the subclasses and define it more simply. This is what I've tried...but it doesn't work.

  MasterModel.subclasses.each do |master_model|
    resources master_model.name.underscore.to_sym, :controller => 'master_models'
  end
NothingToSeeHere
  • 2,253
  • 5
  • 25
  • 57

1 Answers1

0

It probably doesn't work because the subclasses for MasterModel haven't been auto-loaded yet, so that method just returns an empty array. Try explicitly requiring the models above your loop and see what happens.

Brad
  • 718
  • 4
  • 19
  • What is the syntax to require my models? – NothingToSeeHere Dec 02 '16 at 00:55
  • I've searched for how to explicitly require the models and I'm at a loss. Do you have any insight? – NothingToSeeHere Dec 02 '16 at 23:46
  • Sorry, didn't see your first comment. Just for purposes of testing the theory, I would first do this: `puts 'here' MasterModel.subclasses.each do |master_model| puts master_model.to_s resources master_model.name.underscore.to_sym, :controller => 'master_models' end ` – Brad Dec 02 '16 at 23:49
  • I seem to not know how to format comments here. Anyway, the idea is to do two things: 1) Verify the loop is not running because there are no subclasses. Then, 2) just do a full `require /absolute/path/to/one/model` in routes.rb. After step 2, the `puts` from step 1 should show the single model that you've required. – Brad Dec 02 '16 at 23:52