New to rails and I have what I think is a basic question.
In an admin view, there will be varying operations done on different data models. I have a layout “admin” which has various tabs the user clicks to load forms to edit various sets of data.
Should the controller for everything that can be edited in this view be in admin_controller (ie, have an edit_product, edit_user…), or is it better to leave the functions in the controller for each model (say users_controller, products_controller, orders_controller) and specify in the controllers to use the admin layout?
I’m working through my first rails project, and it seems either way works, but obviously I want to follow the right convention going forward so any hint, or a link to an article about this topic would be appreciated.
Thanks,
The proper Rails way to do this would be to use
Namespaces. I’ll give an example below:Inside your
controllersfolder, you add a new folder calledadmin, and for each model you want to edit as an admin, add a controller. Here is a basic blog application:Notice the new folder layer within our
controllerfolder. Inside each of these files, you’ll change the definition of the class, from:to:
Now, within your
congif/routes.rbfile, you can namespace your routes to the admin namespace, like so:Now, you can go to a URL such as:
http://localhost:3000/admin/users/1and you’ll have access to whatever you specified in the admin version of your users controller.You can read more in this StackOverflow question, and read up on the Routes here.