Rails, why does a union return an array with non-uniq values?

I use the example with Rails 3, but I believe that this is true for Rails 2.3.

Suppose I have a City model in which there are many places. I am trying to find Cities that have locations.

I am using the following code:

City.joins(:locations)

But the output array is:

=> [#<City id: 5, name: "moscow", created_at: "2010-07-02 15:09:16", updated_at: "2010-07-02 15:09:16">, #<City id: 5, name: "moscow", created_at: "2010-07-02 15:09:16", updated_at: "2010-07-02 15:09:16">, #<City id: 5, name: "moscow", created_at: "2010-07-02 15:09:16", updated_at: "2010-07-02 15:09:16">, #<City id: 5, name: "moscow", created_at: "2010-07-02 15:09:16", updated_at: "2010-07-02 15:09:16">]

The length of the array is 4 (the number of seats in Moscow).

In which case can this be useful? For what purpose are four copies of the same object in the output array?

I can use City.joins (: locations) .uniq, but I have lost the isl agility.

I have two questions:

  • Why does the union return a non-unique array?
  • What do you prefer to use instead of compounds for this purpose?
+5
source share
1

, , , , , . , (Rails , belongs_to/has_many ).

City.joins(:locations) . - (Location.joins(:city)) , .

, , City.select(:city).joins(:locations).group('cities.id') select() , group() .

+16

All Articles