← Back to Upcase

Interview question


(Charlieanna) #1

I was asked in an interview what MVC was. I said MVC is an architecture in which you try to keep the view logic away from the controller logic away from the model logic. All the database queries goes in the models.

But then I was asked in the def index we often do @users = User.all so isnt this a part of the business logic and why should this go in the controller?

Then I was asked if I were to put conditionals then where will I put the logic and I said models.

The interviewer asked me why this difference. User.all in the controller but User.all with conditionals in the model.

I am still confused with this question but I loved the question.
If someone could explain it that would make my day.


(Oto Hlincik) #2

I believe that you were on the right track with your answer about the MVC but there is a bit more detail that needs to go to it. Actually, the names of the ‘components’ explain what they are all about: Model encapsulates the business logic relating to the models (your application data), View takes care of your presentation and user interfaces, and Controller takes care of the actual ‘flow’ of your application (in general, it ties together your data and presentation and in some cases takes care of making some decisions).

Theoretically the MVC architecture should work like the following (in majority of cases): Controller receives a request to do something and figures out what Model should be used to either retrieve, save, or process particular data, then it selects the appropriate View and renders the data or user interface necessary.

Now going back to your question. The @users = User.all should in majority of cases be in your Controller. That’s where your application ‘decides’ that in fact the users data should be retrieved using the User model. The actual business logic of what the data is, which columns it contains, how it should be validated, etc. that’s all encapsulated in your model.


(Luís Ferreira) #3

It is extremely hard to write completely decoupled code following rails’s MVC, for instance, by using a model instance in the view, your making the view be aware of business logic, if what you want is to have complete separation of responsibilities you might want to take a look at this article.

An easier change you can make if you don’t want to call User.all from the controller is to have an intermediate layer of services such as GetsUser, which can have an all method. This will make sure that the controller is not coupled to the model, nor to the DB, since the model probably inherits from AR.

As oto said, controllers are about controlling flow, parsing http requests and deciding what to render or where to redirect to. You should try to move all logic out of it, may it be into a model, a service, DTO, etc…

Not sure if this answers your question fully, but I hope it helps.