Search code examples
ruby-on-railscontrollers

When should I create a separate controller instead of a custom action in Rails?


Consider an example where I have an Orders model. Triggering the index action shows all of the orders in the system.

Now I want to have a separate page that displays a chart of all refunded orders and another page that displays all cancelled orders--not only is there now a filter, but a whole new view as well.

What would be a best practice:

1.) Creating new actions in OrdersController for each report (e.g., refund_report and cancelled_report)

2.) Creating new controllers for each report (e.g., RefundReportController, CancellationReportController) with a single show action?

3.) Creating one new controller for all reports (e.g., OrderReportsController) and an action for each report (e.g., refunds, cancellations, etc.

Or is there another paradigm I'm missing altogether?


Solution

  • Go with #1: create actions within OrdersController for each report. This is simple, and it makes sense that a resource (an Order) would have multiple views into it through its associated controller. You're not asking for anything specific to one of these reports yet and it's a good/simple pattern that 1 :get action (and route) corresponds to 1 view.

    If, in the future, you find that you're doing a few things specific to a report then consider giving that report its own controller. But that may never happen and no need to abstract early and weigh yourself down now.

    Basically, create a new Controller when you want to start thinking of that something as its own entity with its own actions. Don't break something out into a new controller just because the default REST options don't provide a specific member action for what you need.