【发布时间】:2011-03-11 15:11:10
【问题描述】:
我在 Rails 3 中使用了示例,但我相信 Rails 2.3 也是如此。
假设,我有一个模型 City,它有很多 Locations。我试图找到有位置的城市。
我使用以下代码:
City.joins(:locations)
但是输出数组是:
=> [#<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">]
数组长度为 4(莫斯科的位置数)。
在什么情况下有用?输出数组中一个对象的 4 个副本的目的是什么?
我可以使用 City.joins(:locations).uniq,但我失去了 arel 的敏捷性。
我有两个问题:
- 为什么连接返回非唯一数组?
- 为此目的,首选使用什么来代替连接?
【问题讨论】:
标签: ruby-on-rails unique join