一个控制器使用另一个控制器的视图进行渲染

时间:2009-06-18 14:55:52

标签: ruby-on-rails view controller render

我有QuestionController 我现在有一个AnotherQuestionController,其中的动作应该使用app / views / question /中的模板和部分进行渲染 这可能吗?看起来应该是这样。

我试过

render :template => "question/answer"

但answer.html.erb包含部分内容,我收到错误,如

“视图路径中缺少模板another_question / _my_partial.erb”

那么有没有办法告诉Rails“将AnotherQuestionController视为其QuestionController并在app / views / question中查找视图和部分”? 或者我是否必须创建app / views / another_question - 这将导致重复(这不能是Rails方式)。

由于

4 个答案:

答案 0 :(得分:52)

模板渲染实际上应该有效

 render :template => "question/answer"

你遇到的问题是看到错误的地方。修复很简单,只需在任何共享模板中使您的部分绝对。例如,question / answer.html.erb应该有

<%= render :partial => 'question/some_partial' %>

而不是通常的

<%= render :partial => 'some_partial' %> 

答案 1 :(得分:12)

您可以通过以下方式实现:

render 'question/answer'

答案 2 :(得分:0)

您可以尝试我在http://github.com/ianwhite/inherit_views/tree/master的答案中提到的inherit_views插件(this question)。

答案 3 :(得分:0)

Rails使用前缀列表来解析模板和部分。正如您在另一个答案中所建议的那样,尽管您可以显式指定前缀(“问题/答案”),但是如果模板本身包括对其他部分的不合格引用,则此方法将失败。

假设您有一个ApplicationController超类,而QuestionController继承自它,那么Rails查找模板的位置依次是“ app / views / question /”和“ app / views / application /”。 (实际上,它也会在一系列视图路径中显示,但是为了简单起见,我将其忽略了。)

给出以下内容:

class QuestionController < ApplicationController
end

class AnotherQuestionController < ApplicationController
end

QuestionController._prefixes
# => ["question", "application"]
AnotherQuestionController._prefixes
# => ["another_question", "application"]

解决方案#1。将部分内容放置在“ app / views / application /”下,而不是“ app / views / question /”下,两个控制器都可以使用。

解决方案2。从QuestionController继承(如果适用)。

class AnotherQuestionController < QuestionController
end
=> nil
AnotherQuestionController._prefixes
# => ["another_question", "question", "application"]

解决方案#3。定义类方法AnotherQuestionController :: local_prefixes

这是在Rails 4.2中添加的。

class AnotherQuestionController < ApplicationController
  def self.local_prefixes
    super + ['question']
  end
end
AnotherQuestionController._prefixes
# => ["another_question", "question", "application"]
相关问题