From: Trish Date: 2010-08-04T01:22:27+09:00 Subject: Re: Complex associations Thanks for the input. I will give these a shot. Sorry about the example... it was just my way of trying to simplify what we have going on in our application. StoreType, Store, Department, and Product are just models I "invented" to get my problem across :) After digging into this further, it appears that the *real* issue I'm trying to solve is how to get the store_products and department_products in one SQL statement and be able to sort on an Store attribute (i.e. Store Name). This is for an existing project that used to do this with pure SQL, and had a lot of hard-coding for sort orders. The end result is for a report that has multi-sortable columns that rely on MySQL ORDER BY to get the proper orders. Also... sorry about the double post (to those who may have noticed :) ) It did not appear that my original posted, so it's not that I was being impatient, it's that I was blind :) Thanks! Trish On Aug 3, 9:58 am, Brian Candler wrote: > Trish wrote: > > Is there a way to do this? > > Named or anonymous scopes perhaps. See these posts:http://blog.ethanvizitei.com/2009/05/joins-and-namedscopes-in-activer...http://webjazz.blogspot.com/2008/06/anonymous-scope-unknown-cousin-of... > > So I'm guessing something like this (completely untested): > > class Store >   def products >     Product.scoped(:joins => :department, >       :conditions=>["products.store_id=? or (products.department_id = > departments.id and departments.store_id=?)", id, id]) >   end > end > > And the reverse: > > class Product >   def store >     if store_id >       Store.find(store_id) >     elsif department_id >       Store.find_first(:joins => :department, >         :conditions=>["stores.id = departments.store_id and > departments.id = ?", department_id]) >     end >   end > end > > I'm not quite sure I've understood the model though. A particular > product can only be sold in one department or one store? If another > store wants to stock it as well, do you need another Product row? > > -- > Posted viahttp://www.ruby-forum.com/.