Search code examples
ruby-on-railsrubyactioncontrollers

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


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

I fetched this definition from the official rails guide:

A controller's purpose is to receive specific requests for the application. Routing decides which controller receives which requests. Often, there is more than one route to each controller, and different routes can be served by different actions. Each action's purpose is to collect information to provide it to a view.

I am confused. Please, make it as simple as possible since I am newbie!

Thanks!


Solution

  • 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