从另一个控制器调用渲染

Call rendering from another controller

我有一个带有 3 个控制器的 rails 应用程序:

categoriessubcategoriesall

两个第一次从数据库中获取数据并通过

渲染
render "list"

最后一个应该得到第一个控制器的结果,第二个控制器的结果并渲染它们。

简化示例:

# categories_controller.rb
class CategoriesController < ApplicationController
    def index
        render "list"
    end
end 

# subcategories_controller.rb
class SubcategoriesController < ApplicationController
    def index
        render "list"
    end
end 

# all_controller.rb
class AllController < ApplicationController
    def index
        # should render the both and join them
    end
end 

# list.html.erb
this is the list 

结果:

/category
=> "this is the list "

/subcategory
=> "this is the list "

/all
=> "this is the list this is the list "

我试着打电话给

 render "subcategory"
 render "subcategory/index"

但似乎没有任何效果。

你有什么想法吗?

谢谢,


以前的方法如下:

# categories_controller.rb
class CategoriesController < ApplicationController
    def self.getAll
        return Category.all
    end
    def index
        @data = CategoriesController.getAll
        # some logic here
        render "list"
    end
end 

# subcategories_controller.rb
class SubcategoriesController < ApplicationController
    def self.getAll
        return Category.all
    end
    def index
        @data = SubcategoriesController.getAll
        # some logic here
        render "list"
    end
end 

# all_controller.rb
class AllController < ApplicationController
    def index
        @categoriesData = CategoriesController.getAll
        @subcategoriesData = SubcategoriesController.getAll
        render 'all'
    end
end 

# list.html.erb
<%= @data %>

# all.html.erb
<%= @categoriesData %>
<%= @subcategoriesData %>

但是我必须重写一部分已经存在的逻辑...

您需要在 all 控制器操作中显式构建所需的输出,而不是尝试加入其他操作的输出。

两种方法:

  1. 通过两次数据库调用检索您想要的项目,将它们连接到一大组列表项中,然后像在其他操作中一样呈现列表。

    class AllController < ApplicationController
        def index
            categories = Categories.all
            sub_categories = Subcategories.all
            @all = categories + sub_categories
        end
     end
    
  2. 检索两组数据,使 list.html 页面调用一个名为 _sub_list.html 的部分,然后为 all 页面创建一个名为的新模板all.html,它渲染新的部分两次,每组数据一次。

    class AllController < ApplicationController
        def index
            @categories = Categories.all
            @sub_categories = Subcategories.all
        end
     end
    

跨控制器重用逻辑。使用问题:

module SharedLogic
  extend ActiveSupport::Concern

  def useful_function
    # some code...
  end
end

class SubcategoriesController < ApplicationController
  include SharedLogic

  def index
    @data = SubcategoriesController.getAll
    # some logic here
    useful_function

    render "list"
  end
end