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
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With