What's the difference between controllers and actions in ruby on rails?

前端 未结 3 1580
误落风尘
误落风尘 2021-02-03 09:57

Can anybody tell me the difference between controllers and actions in ruby on rails?

I fetched this definition from the official rails guide:

A co

3条回答
  •  执念已碎
    2021-02-03 10:43

    Controllers are just Ruby Class files which have a series of instance methods inside


    Basic Explanation

    Rails controllers are basically files where actions (methods) are kept

    Each time you access a Rails app, you're sending a request to the system. The various technologies inside Rails route that request to a certain action, where your code can use the passed data to perform some sort of action (hence the name). The actions are kept inside controllers to give the application structure

    So if you access http://yourapp.com/users/new, it tells Rails to load the new method in the users controller. You can have as many actions in the controllers as you want, but you have to tell the Rails routes system they are there, otherwise they won't be accessible


    Proper Explanation

    Rails Controllers are just Ruby Classes, storing a series of actions

    The "actions" (instance methods) work on passed data (params) to create objects that can either be passed to the model, or used inside other methods

    Whenever you send a request to Rails (access a URL), it first uses the ActionDispatch middleware to send your request to the correct Class (controller) instance method (action), and then your code does something with that data

    Your job as a dev is to connect the right controllers with the right models, presenting the right data the user at the right time

提交回复
热议问题