When to create a new controller in rails

前端 未结 4 786
渐次进展
渐次进展 2020-12-15 03:23

I\'m wondering when you know that you need to create a controller in a rails application.

For example, I\'m going through the tutorial in Agile Web Development with

4条回答
  •  失恋的感觉
    2020-12-15 04:06

    Obviously, there's no hard-and-fast rule; but I think it's helpful to think in terms of what the three different parts of MVC represent (or "do"):

    • Models represent the data and data-logic backend
    • Controllers let the user interact with the models
    • Views are what the user sees when the user interacts via a Controller

    So different controllers would be used for when you want to do different (categories of) things.

    For instance, in the AWD book, the Depot application works (broadly) by manipulating and storing Products - so it has a Product model.

    There are two distinct ways of interacting; as the owner of the Depot (adding products, adjusting prices and stock...) or as a customer (adding products to your cart, checking out...). So it has an Admin controller for the former, and a Store controller for the latter.

    Another reason, and one which will often tie into the first, is if your controllers need different wrapping. For instance, you need to authenticate the user before doing any Adminy stuff, but you don't for Customer-based things. So you can separate the actions into two controllers, and put a before_filter on the Admin one to handle authentication.

提交回复
热议问题