如何运行另一个控制器的创建操作
我正在使用 Rails 开发 iPhone 应用程序的后端。这是我第一个真正的 Rails 项目。
这个应用程序是一种项目管理应用程序。在应用程序中,人们可以创建用户帐户,同时他们可以选择创建第一个项目。因此,当用户提交信息时,我的用户控制器会收到一个包含用户信息和项目信息的参数的发布请求。
所以我现在要做的是将用户信息与所有属性存储在数据库中,但我还检查参数是否包含任何项目信息,如果包含,我想运行项目控制器的创建操作。
我知道这可以通过运行两个单独的发布请求或通过在用户模型和项目模型之间建立关联,然后从用户控制器运行 Project.create 来完成,但因为我认为这种方式本质上重复了项目创建操作应该做的事情无论如何,我想保持干燥并以某种方式运行项目控制器的创建操作。
这在rails中可能吗?至少在php和zend中是可能的。
I am working on the backend of a iphone application with rails. This is my first real project with rails.
This app is kind of a project management app. In the app it is possible for people to create a user account and at the same time they can choose to create a first project. So when users submit their information, my users controller receives a post request with params containing both the user info and the project info.
So what I am doing now is storing the user info with all attributes inside the database but I also check if the params contains any project info, and if it does I want to run the project controller's create action.
I know that this can be done by running two separate post requests or by making associations between the user model and the project model and then just run Project.create from the user controller but since I think this way essentially duplicates what a project create action should do anyway, I instead want to stay dry and just somehow run the projects controller's create action.
Is this possible in rails?, it is at least possible with php and zend.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您有要在控制器之间共享的代码,您可能希望将其提取到模块中并将其“混合”作为包含内容。
然后就可以看到“mixed-in”模块的效果了:
If you've got code that is to be shared between controllers, you probably want to look to extracting it to a module and "mixing it in" as an include.
Then you can see the effect of the "mixed-in" module:
你不应该那样做。
瘦控制器意味着控制器操作的代码应该很小。
使用各种控制器操作是可能的,并且确实可能会使您特定操作的代码变小,但需要权衡。您正在增加耦合。您正在使操作的代码依赖于另一个控制器。
永远不要那样做。如果您的控制器需要做其他控制器也可以完成的事情,那是可以的。将操作视为用例,但可能具有相似性,但它们可能不相关。
只是抽象为辅助方法,抽象有意义。
You should not do that.
Skinny controller means that the code of controller actions' should be small.
Using various controller actions is possible and indeed may make you particular action's code small, but there is a tradeoff. You are increasing Coupling. You are making an action's code dependant of another controller.
Never do that. If you controller need to do something that is also done by other controller, that is OK. Think of actions like use cases, but might have similar, but they might be not related.
Just abstract to a helper method what makes sense to abstract.
只需尝试通过
ControllerName.new(env).create
调用它,看看会发生什么;-)Just try calling it via
ControllerName.new(env).create
and see what happens ;-)