Using Rails Service Objects

If you're developing web apps using Ruby on Rails, you probably already know that Rails is an MVC (Model-View-Controller) framework, which means that you have your Models responsible for data, Views responsible for templates, and Controllers responsible for request handling. But the bigger your app gets, the more features it has - the more business logic you will have. And here comes the question, where do you put your business logic? Obviously, it's not viewed that should handle it. Controllers or Models? That will make them fat and unreadable pretty soon. That's where Service Objects come to the rescue. In this article, we'll find out what are Rails Service Objects and how you can use them to make your app cleaner and keep it maintainable.

Let's say you have a project for handling cab trips; we'll take a look at the particular controller action, which updates trip records. But it should not only update trips based on user input params (e.g., starting address, destination address, riders count, etc.), but it should also calculate some fields based on those params and save them to the database. So, we have a controller action like this:

CategoriesUncategorized