0
votes

Let's assume I have two Rails ActiveRecord models, CarType (make/model of car) and Car (instance of a CarType). Car *belongs_to* CarType, and CarType *has_many* Cars.

I want a list of Cars, but only with unique CarTypes (no duplicate CarTypes in the results).

Basically, I want the results of:

CarType.find(:all, :include => [:cars])

...but cast as a collection of Car objects instead. How can I accomplish this?

EDIT

I started solving this by executing the CarType.find statement above, reverse-engineering Rails' generated SQL code (Rails actually produces two SQL statements) and then using Car.find_by_sql, but I feel the solution becomes very bulky.

1
So you want to retrieve only one car per CarType? - bassneck
Yes, correct: just one Car per CarType. Side question: would sort order affect which Car (since there can be multiple) would be selected for each CarType? - Tom Söderlund

1 Answers

1
votes

I think, Cars.group("cartype_id") is what you are looking for. And answering your side question, afaik sorting is applied after the group by.