Best way of sorting/grouping objects

I have a Model called Page, which has a column called page_type. I want to display all pages by page type (which can change/be added).

What is the best way of doing this? I was, in the view looping through each page_type, then doing an SQL search for a Page with that page_type. But I don't want to call Models through the View..

I tried to create a laid out like this:

@hash[:type1] = {:object1_id => object, :object2_id => object } @hash[:type2] = {:object1_id => object, :object2_id => object }

etc.

Then using a partial to go through the types.. but I'm getting errors.

Anyone have a good idea of how to do this?

Thanks

Are you looking for something like this?

@pages = Page.all(:order => 'page_type')

"order" is just a SQL ORDER fragment. Then display it in your view with:

= render :partial => 'page', :collection => @pages

I'm not sure if that's too simplistic of an approach. Does that help?

Angelo

That could work. But I need it to order by page_order also. I would like to group them into 3 groups then sort them by that. In the end I want it to look something like this in html...

TYPE ONE Page 1 Page 2

TYPE TWO Page 1 Page 2

Before I was doing something like this (I had an array of each page type called page_types):

<% page_types.each do |t| %>     <%= t %>'s    <% Page.find(:all, :conditions=>{:page_type=>t}, :order=>position %>      etc.   <% end %> <% end %>

By any chance do you have a model named PageType? If you, you could set up a relationship between PageType and Page:

page.rb: belongs_to :page_type

page_type.rb: has_many :pages

Then display it with:

your_controller.rb: @page_types = PageType.all

your_view.html.haml (or .erb, etc.) - @page_types.each do |page_type|   %h1= page_type.name   %ul     = list_of page_type.pages do |page|       = page.name

If you don't already have a PageType model, or don't want to introduce another model, you could probably use:

@page_types = Page.all(:order => 'page_type', :group => 'page_type')

and then play around with the result of that. (At least I think that's correct… haha, sorry if it's not)

Good luck, Angelo

Thanks Angelo! That is a great idea. In the long run that would probably make more sense. But in the meantime I'll look into the :group fix. What exactly does that do?