Reputation: 2842
I have a rails application with 3 controllers :
categories
, subcategories
, all
The two firsts fetch data from the db and render it via
render "list"
The last one should get the result of the first controller, the result of the second one and render them.
Simplified example :
# 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
Result :
/category
=> "this is the list "
/subcategory
=> "this is the list "
/all
=> "this is the list this is the list "
I tried to call
render "subcategory"
render "subcategory/index"
But nothing seems to work.
Do you have an idea?
Thanks,
A previous approach was the following :
# 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 %>
But I have to rewrite a part of logic that is already there ...
Upvotes: 1
Views: 201
Reputation: 14949
You need to explicitly build the output that you need in the all
controller action, rather than trying to join the outputs of other actions.
Two approaches:
Retrieve the items you want with two database calls, join them together into one big set of list items, then render the list as in the other actions.
class AllController < ApplicationController
def index
categories = Categories.all
sub_categories = Subcategories.all
@all = categories + sub_categories
end
end
Retrieve both sets of data, make the list.html
page call a partial called _sub_list.html
or something, then have a new template for the all
page called all.html
, which renders the new partial twice, once for each set of data.
class AllController < ApplicationController
def index
@categories = Categories.all
@sub_categories = Subcategories.all
end
end
To reuse logic across controllers. use a concern:
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
Upvotes: 3