Should frontend and backend be handled by different controllers?

后端 未结 4 396
自闭症患者
自闭症患者 2021-02-01 09:52

In my previous learning projects I always used a single controller, but now I wonder if that is good practice or even always possible.

In all RESTful Rails tutorials the

4条回答
  •  鱼传尺愫
    2021-02-01 10:23

    I asked myself this question almost every time when I get a new project. I usually choose one of the two solutions:

    1). Single Controller, Single View

    I almost never choose this solution now a days unless the project is really simple, and only one or two types of users. If you get multiple user types it is better to use solution # 2. Although this solution may be appealing because you think you save yourself some time by writing less code, but in the end, your controller and view will grow in complexity. Not to mention all the edge cases you have to consider. This usually means bugs.

    My company once had to rescue a failed project, it had 3 user types. (admin, business, and member). They used solution #1. The code was in a horrible condition, ( and that's why we were asked to rescue this project) We were jokingly saying it is not MVC, it was MMM. (Model-Model-Model) This is because business logic was not properly extracted and put into models, but spread in controllers and views as well.

    2). Multiple Controller, Multiple Views

    I use this solution more and more these days. I usually namespace the controllers with user types. For example:

    In "app/controllers"

    class BookController < ApplicationController
    end
    

    and in "app/controllers/admin"

    class Admin::BookController < Admin::BaseController
    end
    

    I only need to consider regular users when I fill in BookController, and only need to consider admin users when I fill in Admin::BookController

    I'm not sure if there are better ways, but this is what I learned from a dozen projects I've done so far...

提交回复
热议问题