I assume that you have two (or more) seperate models for children objects, so your Parent
model looks like this:
class Parent < ActiveRecord::Base
has_many :dogs
has_many :cats
end
To sort them and get them generally as children
you can write method (similar to @gertas answer):
def children
@children ||= (self.dogs.all + self.cats.all).sort(&:created_at)
end
and put it in Parent
model. Then you can use it in controller:
@parent = Parent.find(params[:id])
@children = @parent.children
Now we'll try to display them in a view. I assume that you have created two partials for each model _cat.html.erb
and _dog.html.erb
. In view:
<h1>Children list:</h1>
<% @parent.children.each do |child| %>
<%= render child %>
<% end %>
It should automaticaly find which partial should be used, but it can be used only if you follow Rails way. If you want to name partials in different way, or store it in different directory, then you would have to write your own methods that will choose correct partial based on type od object.