Rails Model, View, Controller, and Helper: what goes where?

后端 未结 10 1016
不思量自难忘°
不思量自难忘° 2020-11-30 15:59

In Ruby on Rails Development (or MVC in general), what quick rule should I follow as to where to put logic.

Please answer in the affirmative - With Do put this h

10条回答
  •  被撕碎了的回忆
    2020-11-30 17:01

    Well, it sort of depends upon what the logic has to deal with...

    Often, it makes sense to push more things into your models, leaving controllers small. This ensures that this logic can easily be used from anywhere you need to access the data that your model represents. Views should contain almost no logic. So really, in general, you should strive to make it so that you Don't Repeat Yourself.

    Also, a quick bit of google reveals a few more concrete examples of what goes where.

    Model: validation requirements, data relationships, create methods, update methods, destroy methods, find methods (note that you should have not only the generic versions of these methods, but if there is something you are doing a lot, like finding people with red hair by last name, then you should extract that logic so that all you have to do is call the find_redH_by_name("smith") or something like that)

    View: This should be all about formatting of data, not the processing of data.

    Controller: This is where data processing goes. From the internet: "The controller’s purpose is to respond to the action requested by the user, take any parameters the user has set, process the data, interact with the model, and then pass the requested data, in final form, off to the view."

    Hope that helps.

提交回复
热议问题