Ruby on Rails: Five tips for cleaner controller code

TJ Oyeniyi
Austin Startups
Published in
2 min readApr 9, 2018

--

Source

1. Keep controller actions small and focused solely on receiving a request and returning a response.

  • Rule of thumb: your controller actions should be no more than 5–7 lines of code.

2. For handling requests, move the business logic out of controllers and into plain old Ruby objects like Service objects (app/services) or models (app/models) that don’t inherit from ActiveRecord, and call that in your controller to handle the business logic.

3. Don’t use action filters or instantiate objects unless you absolutely need to(eg.: your view needs access to it, you need to do a check before the request hits the controller action, etc.)

  • You typically see developers use an action filter to set @some_data , but you can just define your method to return the appropriate data without it being stored in an instance variable.
  • Only instantiate one object per view. That object should be defined in a way that handles whatever messages/data you need in your view.

4. For your error status codes, only return 400 or 404 so you don’t leak potentially useful information through any other status code.

  • Stay away from the other 4** status codes. They can potentially reveal useful information.
  • Reference

5. Create new controllers/nested resources for any action that falls outside of the standard CRUD actions, which now has its own default crud actions.

--

--