这听起来很奇怪,但请听我说...我需要能够向我的其他控制器之一发出相当于 POST 的请求。SimpleController
基本上是更详细的控制器的简化版本。我怎样才能适当地做到这一点?
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
也许我想多了,但我不知道该怎么做。
Rails应用程序(或任何遵循相同模型-适配器-视图模式的Web应用程序)中的控制器间通信是您应该主动避免的。当你试图这样做时,认为这是一个迹象,表明你正在与构建你的应用程序的模式和框架作斗争,并且你依赖的逻辑已经在应用程序的错误层实现。
正如@ismaelga评论中所建议的那样;两个控制器都应该调用一些公共组件来处理这种共享行为,并保持控制器"瘦"。在 Rails 中,这通常是模型对象上的一种方法,特别是对于您在这种情况下似乎担心的那种创建行为。
你不应该这样做。您要创建模型吗?那么在模型上有两个类方法会好得多。它还更好地分离了代码。然后,您不仅可以在控制器中使用这些方法,还可以在将来的后台作业(等)中使用这些方法。
例如,如果您正在创建人员:
class VerboseController < ApplicationController
def create
Person.verbose_create(params)
end
end
class SimpleController < ApplicationController
def create
Person.simple_create(params)
end
end
然后在人物模型中,你可以像这样:
class Person
def self.verbose_create(options)
# ... do the creating stuff here
end
def self.simple_create(options)
# Prepare the options as you were trying to do in the controller...
prepared_options = options.merge(some: "option")
# ... and pass them to the verbose_create method
verbose_create(prepared_options)
end
end
我希望这能有所帮助。