keith raterink
2006-Jan-13 20:37 UTC
[Rails] Locating Objects by associated object.properties
I am just getting the hang of this, so forgive me if this is a stupid question... - I have two models/tables: Owners and Cars - Owners may have many cars. Cars have one owner. - Cars have a property named Color. Question: how do I get a list of all the Owners who have RED cars? I want something like this to work: Owner.find_by_car.color("RED") Thanks for any help! -- Posted via http://www.ruby-forum.com/.
Jules Jacobs
2006-Jan-13 21:01 UTC
[Rails] Re: Locating Objects by associated object.properties
# find the owner with id = 3 @owner = Owner.find(3) # find all cars that belong to this owner AND have a red color @red_cars = @owner.cars.find(:all, :conditions => [''color = ?'', ''red'']) I think this works. Jules -- Posted via http://www.ruby-forum.com/.
Jules Jacobs
2006-Jan-13 21:05 UTC
[Rails] Re: Locating Objects by associated object.properties
Whoops, this was not what you meant... Owner.find_by_sql(''SELECT owners.* FROM owners, cars WHERE cars.color = "red" AND cars.owner_id = owners.id'') -- Posted via http://www.ruby-forum.com/.
keith raterink
2006-Jan-13 21:12 UTC
[Rails] Re: Locating Objects by associated object.properties
Thanks Jules I guess I was wondering if there was a design-pattern for things like this that do not go all the way down to the SQL. -KRat -- Posted via http://www.ruby-forum.com/.
Mark Beattie
2006-Jan-14 01:40 UTC
[Rails] Re: Locating Objects by associated object.properties
How about: owner has_many :cars car belongs_to :owner red_car_owners = Owner.find( :all, :include => :cars, :conditions => ["cars.colour = ?", ''RED''] ) where "cars.colour" is referring to the cars table directly. Try tailing the development log to get a peek at the left outer join queries put together by the :include eager loading and you''ll see that the cars table is included in the Owner.find query. You can then add conditions which reference the cars table. I think... On Saturday 14 January 2006 6:12 am, keith raterink wrote:> Thanks Jules > > I guess I was wondering if there was a design-pattern for things like > this that do not go all the way down to the SQL. > > -KRat-- Mark Beattie Easy Schedule Management http://easy-online-schedule.com
keith raterink
2006-Jan-14 03:45 UTC
[Rails] Re: Re: Locating Objects by associated object.properties
hot damn mark! I will give it a try...it sure seems to make sense! THANKS -krat -- Posted via http://www.ruby-forum.com/.
Mark Beattie
2006-Jan-14 13:14 UTC
[Rails] Re: Re: Locating Objects by associated object.properties
No worries, hope it helps. cheers, mark On Saturday 14 January 2006 12:44 pm, keith raterink wrote:> hot damn mark! > > I will give it a try...it sure seems to make sense! > > THANKS > -krat-- Mark Beattie Easy Schedule Management http://easy-online-schedule.com