How do I Order on common attribute of two models in the DB?

Posted by Will on Stack Overflow See other posts from Stack Overflow or by Will
Published on 2010-04-05T19:44:51Z Indexed on 2010/04/06 3:33 UTC
Read the original article Hit count: 227

Filed under:
|
|

If i have two tables Books, CDs with corresponding models.

I want to display to the user a list of books and CDs. I also want to be able to sort this list on common attributes (release date, genre, price, etc.). I also have basic filtering on the common attributes.

The list will be large so I will be using pagination in manage the load.

items = []
items << CD.all(:limit => 20, :page => params[:page], :order => "genre ASC")
items << Book.all(:limit => 20, :page => params[:page], :order => "genre ASC")
re_sort(items,"genre ASC")

Right now I am doing two queries concatenating them and then sorting them. This is very inefficient. Also this breaks down when I use paging and filtering. If I am on page 2 of how do I know what page of each table individual table I am really on? There is no way to determine this information without getting all items from each table.

I have though that if I create a new Class called items that has a one to one relationship with either a Book or CD and do something like

Item.all(:limit => 20, :page => params[:page], :include => [:books, :cds], :order => "genre ASC")

However this gives back an ambiguous error. So can only be refined as

Item.all(:limit => 20, :page => params[:page], :include => [:books, :cds], :order => "books.genre ASC")

And does not interleave the books and CDs in a way that I want.

Any suggestions.

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about ruby