Rails模型来调用Controller动作 [英] Rails Model to call Controller action

查看:91
本文介绍了Rails模型来调用Controller动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从模型内部的方法调用控制器内部的操作.这是我用其他语言(在使用MVC框架时)做的很多事情,但是,我从未见过在ruby on rails上做到这一点.该操作不会呈现任何内容,它只会更新一个会话变量.

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.

推荐答案

这不是您通常在MVC模式中通常要做的事情.您的模型实际上应该只包含业务逻辑(和数据访问).您能否提供一些有关您要呼叫的内容以及原因的信息?通常,当您尝试执行此类操作时,有一种气味,即某些东西不在应有的位置.

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:

  • 模型-这些是数据对象 也有用于业务逻辑的方法
  • 控制器-这些是动作 由您的应用采取,它们控制着 模型并告诉他们该怎么做,他们 控制视图以告诉它要做什么 发出
  • 视图-这是界面层, 它可以是任何格式(html,js, xml),但逻辑很少 它
  • 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.

或者,也许您只有一个可以在任何地方使用的方法(它是一个辅助方法,实际上与模型和您的控制器无关).在这种情况下,应将其放在/lib目录中的单独模块中.

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.

是的,会话变量应该只能在Controller中进行触摸/更新.也许您的模型中有太多控件类型的逻辑?如果它实际上是Controller动作的一部分,则可能会重新考虑该逻辑与实际模型之间的紧密关系.

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.

这篇关于Rails模型来调用Controller动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆