Rails,为什么连接返回带有非uniq值的数组?

pet*_*hka 5 join ruby-on-rails unique

我使用Rails 3的示例,但我相信Rails 2.3也是如此.

假设,我有模型城市有很多地方.我试图找到有位置的城市.

我使用以下代码:

City.joins(:locations)
Run Code Online (Sandbox Code Playgroud)

但是输出数组是:

=> [#<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">]
Run Code Online (Sandbox Code Playgroud)

数组长度为4(莫斯科的位置数).

在什么情况下它可能有用?目标是输出数组中一个对象的4个副本?

我可以使用City.joins(:locations).uniq,但我失去了对arel的敏捷.

我有两个问题:

  1. 为什么连接返回非唯一数组?
  2. 为此目的,更喜欢使用而不是连接?

ede*_*ill 16

Join本质上是说将两个表组合在一起并将其视为一个表,然后将所发现的内容发送回去.这意味着它将为您找到城市和位置的每个组合(Rails通过根据模型中的belongs_to/has_many关系进行匹配来帮助您).

这样做City.joins(:locations)可以找到城市中的所有位置.另一种方式(Location.joins(:city))用于查找位置所在的城市.

现在,为了找到具有某些位置的城市列表,您可以尝试使用City.select(:city).joins(:locations).group('cities.id')select()子句告诉它只是将城市带回来,而group()子句告诉它不要带回重复的副本.