40

我有 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

4 回答 4

60

模板渲染应该实际工作

 render :template => "question/answer"

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

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

而不是通常的

<%= render :partial => 'some_partial' %> 
于 2009-06-18T14:58:13.117 回答
14

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

render 'question/answer'
于 2009-06-18T15:13:52.523 回答
1

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"]
于 2019-01-03T17:58:39.957 回答
-1

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

于 2009-06-18T15:07:14.143 回答