Forum: Ruby on Rails Locating Objects by associated object.properties

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Keith R. (Guest)
on 2006-01-13 22:37
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!
Jules J. (Guest)
on 2006-01-13 23:01
# 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
Jules J. (Guest)
on 2006-01-13 23:05
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')
Keith R. (Guest)
on 2006-01-13 23:12
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. (Guest)
on 2006-01-14 03:41
(Received via mailing list)
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
Keith R. (Guest)
on 2006-01-14 05:44
hot damn mark!

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

THANKS
-krat
Mark B. (Guest)
on 2006-01-14 15:15
(Received via mailing list)
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
This topic is locked and can not be replied to.