Where to put this logic? Controller or Model?

Asked

Viewed 1,088 times

3

My application has the following logic:

  • Given a link received, the application takes the attribute <title> of the page and turns this attribute into the link description and saved in the bank.

I put this logic in callback before_save in the Model and it’s working perfectly.

This kind of logic, I should put in the Controller or the correct location is even in the model?

  • How does this link get to the template? I think it’s only fair to set this attribute in a before_save. As long as it’s just setting the value in an attribute.

3 answers

12

According to the MVC standard, all logic, mainly related to database, should be placed in the Model.

Consider the MVC standard as a computer. The Model is the CPU, the View is your monitor and the Controller are the ports / cables.

Views have no logic, just like your monitor. It’s dumb, just displays what the controller (cables / ports) sends to it.

Controllers contain as little logic as possible, as well as cables and ports: They’re just what connects Views and Models.

Models, like the CPU, do all the heavy lifting: it is responsible for any light or heavy logic (the most common being persistence). It is she who handles everything that the Controller sends to her; and the Controller sends it as it did, who will receive, treat, format and manipulate it will be the Model.

  • 3

    That was the best explanation of the MVC concept I’ve seen to date...

  • So Andre... think I have to set up an agenda that is composed of events and locations. Who is responsible to merge these entities and deliver to? :)

  • @Rafaelsoufraz All data manipulation work (probably the SQL Selects) is defined as methods in the Model. The Controller will use the methods of each model to put it together and send it to View.

8

Their models (Models in Rails) are abstractions from the domain of their application. They should not have logics of Crawling, Parsing, things like that.

In my opinion, this logic of extracting information from a link should be carried out by another object, a Service.

Try to get a read on Domain Driven Design, Eric Evans. They also have a good infoQ summary.

More in the Wikipedia.

3


You need to divide this action into:

  • Find the link, make the transformation in the description ( this is the function of the controller )
  • Save to database (this is model function)

  • As a rule, the persistence of the data, saving in the database, is always a function of the model. The logic of your application, depending on the type can go in the View (an initial filter in the data entry for example) and/or in the Controller.

    • 1

      Controllers with logic, other than dealing with requests (their primary function), is anti-pattern. http://codebetter.com/iancooper/2008/12/03/the-fat-controller/

    Browser other questions tagged

    You are not signed in. Login or sign up in order to post.