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"]