Simpleton
Simpleton

Reputation: 6415

Restructuring a controller

I have an interstitial controller action that reroutes admins based on their role attributes. Depending on role types, admins will be directed to one of 4 actions in the same controller (or a catch action). This works fine because in each case, each action has only a single view. But I want to split the views into 10 different pages, and I'm not sure how to structure the controllers.

Each of the 4 cases will have the same 10 actions if they're split into different controllers, and the information will be different, the amount of information will differ depending on role and things like variables will differ slightly.

Should I move each out to its own controller and just use dashboard#index to route them there? Would I have to run rails g controller dashboard/free etc. to add the 4 dashboard controllers in their own sub-folders or is there a wiser way to handle it architecturally?

Routes

match "/dashboard/index" => 'dashboard#index'
match "/dashboard/free" => 'dashboard#free', :as => :dashboard_free
match "/dashboard/standard" => 'dashboard#standard', :as => :dashboard_standard
match "/dashboard/premium" => 'dashboard#premium', :as => :dashboard_premium
match "/dashboard/super" => 'dashboard#super', :as => :dashboard_super

Dashboard controller doing the redirects

def index
  path = case current_admin.role
    when 'free'
      dashboard_free_path
    when 'standard'
      dashboard_standard_path
    when 'premium'
      dashboard_premium_path
    when 'super'
       dashboard_super_path
    else
      no_access_path
  end
  redirect_to path
end

Upvotes: 0

Views: 57

Answers (1)

sockmonk
sockmonk

Reputation: 4255

I would generate separate controllers, using rails g controller dashboard/free etc like you said, but have each of those inherit from your DashboardController instead of ApplicationController. That way if any of the actions are entirely the same, they can just be defined in DashboardController; or you can put common code there for them to share. Depending on what it is, it also might make sense to put shared code in a helper, model, or even a custom module in lib/ that you include in DashboardController.

You also may want to make heavy use of partials in the views, so that common view code can be shared as well.

Upvotes: 1

Related Questions