我有一个名为“show”的 Controller 的 View 。在该 View 中,我想呈现另一个 Controller View 的内容 - 显然,该 View 上的表单的逻辑也与它所属的 Controller 对话。我该怎么做呢?我对 Rails 还很陌生,我对这个框架还不是 100% 有信心。
您几乎可以将它们视为 View 中的“小部件”。我知道您可以使用以下方法在 View 上呈现来自同一 Controller 的操作:
render :action => "show_home_page", :layout=> false
但我需要它来呈现来自另一个 Controller 的 Action ( View )。
IE。
I have a view, which is rendered onto a layout. That view, belongs to controller A. I need to render the "index" and "new" views from controller B inside the original view (above)
.
最佳答案
您问题中的术语有点困惑。如果在一个 Controller 中,并且您想在另一个 Controller 中的另一个操作方法中执行代码并呈现其模板,则应该重定向_到该操作。假设另一个 Controller 称为 ContractsController
redirect_to :controller => "contracts", :action => "show_home_page"
如果您只想使用来自另一个方法的 View 模板作为您的操作的响应,您只需要在渲染参数中添加 Controller 名称的前缀。这不会调用操作,它只会使用其模板。
例如,如果模板位于契约(Contract) Controller 的文件夹中。
render :action => "/contracts/show_home_page", :layout=> false
我认为在这种情况下,您实际上是在谈论部分内容,看起来像
render :partial => "/contracts/show_home_page"
然而,我看到您在这里掌握的是您实际上想要调用多个操作方法来呈现单个页面。这不是它的工作原理。您将不得不设置模板将在单个操作中引用的对象。这是大多数 Rails 开发人员在模型中放置大量代码的原因之一,因此设置不会在整个 Controller 中重复。
但还有另一种方式...... 的魔力所在JavaScript 进来。
在您的页面中,创建一个这样的函数:
<script type="text/javascript" language="javascript">
function load_categories() {
<%= remote_function(:url => {:controller => "categories", :action => "list"},
:update => "categories")%>
};
</script>
如果您在页面的 onload 中调用它,它将用 id 为“categories”的 div 替换为引用的操作的响应。
关于ruby-on-rails - 在 Rails 中将部分从一个 Controller 的 View 渲染到另一个 Controller 的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1767876/