Rails:如何在内部 POST 到另一个控制器操作? [英] Rails: How to POST internally to another controller action?

查看:23
本文介绍了Rails:如何在内部 POST 到另一个控制器操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这听起来很奇怪,但听我说完...我需要能够向我的其他控制器之一发出 POST 请求.SimpleController 基本上是更详细的控制器的简化版本.我该如何适当地做到这一点?

This is going to sound strange, but hear me out...I need to be able to make the equivalent of a POST request to one of my other controllers. The SimpleController is basically a simplified version of a more verbose controller. How can I do this appropriately?

class VerboseController < ApplicationController
  def create
    # lots of required params
  end
end

class SimpleController < ApplicationController
  def create
    # prepare the params required for VerboseController.create
    # now call the VerboseController.create with the new params
  end
end

也许我想多了,但我不知道该怎么做.

Maybe I am over-thinking this, but I don't know how to do this.

推荐答案

Rails 应用程序(或任何遵循相同模型-适配器-视图模式的 Web 应用程序)中的控制器间通信是您应该积极避免的事情.当您想这样做时,请将其视为一个迹象,表明您正在与构建您的应用的模式和框架作斗争,并且您所依赖的逻辑已在应用的错误层实现.

Inter-controller communication in a Rails app (or any web app following the same model-adapter-view pattern for that matter) is something you should actively avoid. When you are tempted to do so consider it a sign that you are fighting the patterns and framework your app is built on and that you are relying on logic has been implemented at the wrong layer of your application.

正如@ismaelga 在评论中所建议的那样;两个控制器都应该调用一些通用组件来处理这种共享行为并保持你的控制器瘦".在 Rails 中,这通常是模型对象上的方法,尤其是对于您在这种情况下似乎担心的那种创建行为.

As @ismaelga suggested in a comment; both controllers should invoke some common component to handle this shared behavior and keep your controllers "skinny". In Rails that's often a method on a model object, especially for the sort of creation behavior you seem to be worried about in this case.

这篇关于Rails:如何在内部 POST 到另一个控制器操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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