views:

52

answers:

2

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.

+5  A: 

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:

  • Model - these are data objects that also have methods for business logic
  • Controller - these are the actions taken by your app, they control the models and tell them what to do, they control the view to tell it what to emit
  • View - this the interface layer, it could be in any format (html, js, xml) but it has very little logic to 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.

Jon Smock
The problem is that I have a plugin for authentication and I need to call a method when a user logs in via a remember me function inside the plugin (which bypasses all of the login controller actions - if this wasn't the case, I would obviously change session data here). The need to call a method in the controller is related to analytic tracking and not really anything the user sees.
scott
A: 

If you want call controller action (or cahange session because session is defined as @session variable and it's private) from model you should pass controller instance as a param to model's method so if you do need edit session method may be similar to

def change_session(controller)
  @ses = controller.send :session
  //some actions
end

in controller

def something
  s = Session.new
  s.change_session(self)
  ...
end
Bohdan Pohorilets