[英]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.