I need to call an action inside of a controller from a method inside of a model. This is something I do a lot in other language (when working with the MVC framework), however, I've never seen this done in ruby on rails. The action doesn't render anything, it simply updates a session variable.
A controller is a Ruby class which inherits from ApplicationController and has methods just like any other class. When your application receives a request, the routing will determine which controller and action to run, then Rails creates an instance of that controller and runs the method with the same name as the action.
If you look at book_controller.rb, you will find it as follows − Controller classes inherit from ApplicationController, which is the other file in the controllers folder: application.rb. The ApplicationController contains code that can be run in all your controllers and it inherits from Rails ActionController::Base class.
Ruby on Rails - Controller. The Rails controller is the logical center of your application. It coordinates the interaction between the user, the views, and the model.
The new method lets Rails know that you will create a new object. So just add the following code in this method. The above method will be called when you will display a page to the user to take user input.
That's not really something you would normally do in the MVC pattern. Your Model should really only house business logic (and data access). Can you supply some information about what you're trying to call and why? Usually when you're trying to do something like this, it's a smell that something isn't where it's supposed to be.
This is usually the way I see it:
If you're trying to call something in a controller from a model, it might mean there's too much controlling logic in your model.
Or, perhaps, you've just got a method that could be used everywhere (it's a helper method, and it's actually unrelated from the model and your controller). In this case, you should put it in its own module in your /lib directory.
Edit: Yeah, session variables should probably only be touched/updated in the Controller. Perhaps you have too much control-type logic in your model? Maybe rethink how closely that logic is related to the actual Model if its actually part of the Controller's action.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With