Locating Objects by associated object.properties


#1

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!


#2

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


#3

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’)


#4

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


#5

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 B.
Easy Schedule Management
http://easy-online-schedule.com


#6

hot damn mark!

I will give it a try…it sure seems to make sense!

THANKS
-krat


#7

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 B.
Easy Schedule Management
http://easy-online-schedule.com