views:

45

answers:

3

Relating to my last question here: http://stackoverflow.com/questions/3740724/rails-finding-all-associated-objects-to-a-parent-object

Is it possible to sort multiple separate child objects in Rails by creation date, and then list them? Using the previous example I have a resume with two different has_many child objects, I would like to fetch them and then sort them based on creation date and then use that to display them.

A: 

You can add an accessor method on your parent model:

class Parent < ActiveRecord::Base
  def sorted_children
    children.scoped( :order => 'created_at DESC' )
    # or, in rails3:
    # children.order('created_at DESC')
  end
end

If the natural order for your child model is the date field and you would like to do that everywhere, then just set a default scope on it:

class Child < ActiveRecord::Base
  default_scope :order => 'created_at DESC'
end
Andrew Vit
+1  A: 

As child objects are in different types and they are fetched separately (separate has_many) you have to do sorting in Ruby:

sorted_childs=(@resume.child1_sections.all + @resume.child2_sections.all).sort(&:created_at)

Otherwise you would need to introduce table inheritance with common columns in parent. Then it would be possible to have another has_many for all children with :order.

gertas
+1  A: 

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.

klew
Thanks! This looks like it is putting me on the right track. I really appreciate your help.
thedjpetersen
Thank you this seems to have done the trick
thedjpetersen