Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Do I need a controller for each model? [closed]

I have a Rails app with 4 models. I only access these 4 models in one controller action each. I currently have 4 different controllers to handle these models. I am wondering if it is bad practice that I stuff these 4 actions into one controller.

Current Setup:

class GmDataController < ApplicationController
    def dashboard
      @data = GmData.all
    end
end

class GmRetentionController < ApplicationController
    def dashboard
      @data = GmRetention.all
    end
end

class GsDataController < ApplicationController
    def dashboard
      @data = GsData.all
    end
end

class GsRetentionController < ApplicationController
    def dashboard
      @data = GsRetention.all
    end
end

Proposed Setup:

class DashboardController < ApplicationController
    def gm_data_dashboard
      @data = GmData.all
    end

    def gm_retention_dashboard
      @data = GmRetention.all
    end

    def gs_data_dashboard
      @data = GsData.all
    end

    def gs_retention_dashboard
      @data = GsRetention.all
    end
end
like image 775
user2158382 Avatar asked Sep 26 '13 22:09

user2158382


1 Answers

TL;DR

Do I need a controller for each model?

No, not necessarily. However, having one controller per RESTful resource is a convention for a reason, and you should carefully analyze why that convention isn't meeting your needs before doing something completely different.

Think "Resources," Not Controllers

You appear to be conflating RESTful resources with the Rails implementation of MVC. As a general rule, your controller should contain actions related to a resource. If your application treats a "Dashboard" as a resource, then a single DashboardController might certainly make sense if you're performing RESTful actions on a Dashboard object of some kind.

Conventions Aren't Laws of Physics

Rails uses a lot of conventions in order to map resources in a RESTful way, but sometimes those conventions don't match real-world applications. In such instances, you might find that one controller can handle all the actions you need, or that a single model might serve the needs of multiple controllers.

However, before you bollix up all your MVC layers, it's often useful to spend some time thinking about whether you have conceptually captured the correct resource model for your application. Is your resource really a Dashboard object? Does a Dashboard object really need a Dashboard#gs_data method to represent its behavior, or would GsData#index be semantically more meaningful?

In the end, you don't even have to use Rails in a RESTful way if you don't want to do so. However, you really ought to have a better reason (from an object-oriented analysis viewpoint) than you've laid out in your original question above.

like image 191
Todd A. Jacobs Avatar answered Sep 19 '22 12:09

Todd A. Jacobs