简体   繁体   English

Rails 3:如何从另一个控制器的视图呈现动作

[英]Rails 3: How to render an action from another controller's view

I'm trying to call an action from a different controller's view:我试图从另一个控制器的视图中调用一个动作:

Controller Countries has an action called selectbox which generates a html selectbox from all countries as a partial. Controller Countries有一个称为selectbox的操作,它从所有国家/地区生成一个 html 选择框作为部分。
Controller Customers has an action called new which generates a html form for all the customers attributes. Controller Customers有一个名为new的操作,它为所有客户属性生成 html 表单。 I want to insert the selectbox from Countries#selectbox in this form.我想在这个表单中插入来自 Country Countries#selectbox的选择框。

What would be the right way to achieve this?实现这一目标的正确方法是什么?

You're doing it wrong.你这样做是错的。 If there's a piece of code that is to be reused (such as html selectbox generation), you should put it in a helper and/or use a partial to render the html selectbox part.如果有一段代码要重用(例如 html 选择框生成),您应该将它放在帮助程序中和/或使用部分代码来呈现 html 选择框部分。

Bear in mind this is only good advice if the code is somewhat complex (say, more than one or two lines).请记住,如果代码有些复杂(例如,超过一两行),这只是一个好建议。 Here's a post I found while googling that may help you: helper or partial这是我在谷歌搜索时发现的可能对您有帮助的帖子: 助手或部分

For what you are doing, extracting the code into helper method is the right way to do it.对于您正在做的事情,将代码提取到辅助方法中是正确的方法。 However, if you still want to use am action from another, this is the official Rails plugin you can use:但是,如果您仍想使用来自其他人的 am 操作,这是您可以使用的官方 Rails 插件:

https://github.com/rails/render_component https://github.com/rails/render_component

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

相关问题 在Rails中,从另一个控制器的角度渲染一个动作方法 - In rails render an action method from a view of another controller Rails:如何从另一个控制器呈现部分视图 - Rails: How to render partial view from another controller 我可以在Rails 4中从当前控制器渲染另一个控制器的动作吗? - Can I render another controller's action from my current controller in Rails 4? 如何重定向/渲染到另一个控制器的视图? - How to redirect/ render to another controller's view? 如何在当前视图内渲染另一个页面(Controller Action + View) - How to render another page (Controller Action + View) inside current view 如何将一个控制器的局部视图渲染到轨道上的ruby中的另一个控制器 - How to render partial view of one controller to another controller in ruby on rails 默认情况下,Rails控制器如何渲染该操作的视图 - how does a rails controller render by default the view for that action 如何在Rails 4.2中的动作中呈现不同的控制器/动作? - How to render a different controller / action from within an action in Rails 4.2? 尝试从Rails ApplicationContoller渲染另一个控制器的视图时出现问题? - Issues when attempting render another controller's view from a Rails ApplicationContoller? Rails-在控制器中,如何从其他控制器渲染动作? - Rails - in controller, how to render an action from a different controller?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM