One controller rendering using another controller's views

前端 未结 4 1370
渐次进展
渐次进展 2020-12-14 06:07

I have QuestionController I now have AnotherQuestionController with actions which should render using templates and partials in app/views/question/ Is this possible? Seems l

相关标签:
4条回答
  • 2020-12-14 06:58

    You can achieve it with:

    render 'question/answer'
    
    0 讨论(0)
  • 2020-12-14 06:59

    Rails uses a list of prefixes to resolve templates and partials. While you can explicitly specify a prefix ("question/answer"), as suggested in another answer, this approach will fail if the template itself includes unqualified references to other partials.

    Assuming that you have an ApplicationController superclass, and QuestionController inherits from it, then the places Rails would look for templates are, in order, "app/views/question/" and "app/views/application/". (Actually it will also look in a series of view paths, too, but I'm glossing over that for simplicity's sake.)

    Given the following:

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

    Solution #1. Place the partial under "app/views/application/" instead of "app/views/question/", where it will be available to both controllers.

    Solution #2. Inherit from QuestionController, if appropriate.

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

    Solution #3. Define the class method AnotherQuestionController::local_prefixes

    This was added in Rails 4.2.

    class AnotherQuestionController < ApplicationController
      def self.local_prefixes
        super + ['question']
      end
    end
    AnotherQuestionController._prefixes
    # => ["another_question", "question", "application"]
    
    0 讨论(0)
  • 2020-12-14 07:03

    You could try the inherit_views plugin (http://github.com/ianwhite/inherit_views/tree/master) I mentioned here in the answer to this question.

    0 讨论(0)
  • 2020-12-14 07:07

    Template rendering should actually work

     render :template => "question/answer"
    

    The problem you were having is from the partials looking in the wrong place. The fix is simple, just make your partials absolute in any shared templates. For example, question/answer.html.erb should have

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

    rather than the usual

    <%= render :partial => 'some_partial' %> 
    
    0 讨论(0)
提交回复
热议问题