简体   繁体   English

Rails模型调用Controller动作

[英]Rails Model to call Controller action

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. 这是我用其他语言做的很多事情(当使用MVC框架时),但是,我从未在ruby on rails上看到过这种情况。 The action doesn't render anything, it simply updates a session variable. 该操作不会呈现任何内容,只是更新会话变量。

That's not really something you would normally do in the MVC pattern. 这通常不是你在MVC模式中通常会做的事情。 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 查看 - 这是界面层,它可以是任何格式(html,js,xml)但它的逻辑很少

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. 在这种情况下,您应该将它放在/ lib目录中的自己的模块中。

Edit: Yeah, session variables should probably only be touched/updated in the Controller. 编辑:是的,会话变量应该只能在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. 如果它实际上是Controller的行动的一部分,也许重新考虑该逻辑与实际模型的关系有多紧密。

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 如果你想要调用控制器动作(或者cahange会话因为session被定义为@session变量并且它是私有的)你应该将控制器实例作为参数传递给模型的方法,所以如果你需要编辑session方法可能类似于

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

in controller 在控制器中

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM