Rails,为什么联接返回具有非唯一值的数组? [英] Rails, why joins returns array with non-uniq values?

查看:114
本文介绍了Rails,为什么联接返回具有非唯一值的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

假设,我有一个模型City,它有很多位置.我试图找到有位置的城市.

Suppose, I have model City that has many Locations. I try to find Cities that have 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(莫斯科的位置数).

Array length is 4 (number of locations of Moscow).

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

In what case it can be useful? For what aims are 4 copies of one object in output-array?

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

I can use City.joins(:locations).uniq, but I lost agile of arel.

我有两个问题:

  1. 为什么联接会返回非唯一数组?
  2. 为此,首选使用什么代替联接?

推荐答案

Join本质上说要合并两个表并将其视为一个表,然后将发现的所有内容发回.这意味着它将找到城市和位置的每种组合(Rails会根据模型中的belongs_to/has_many关系进行匹配,以提供帮助.

Join essentially says to combine two tables and treat it like one table, sending back whatever would be found. That means it will find you every combination of city and location (Rails is helping out by matching things up based on the belongs_to/has_many relationship in your models).

执行City.joins(:locations)将用于查找城市中的所有位置.另一种方法(Location.joins(:city))则是查找位置所在的城市.

Doing City.joins(:locations) would be for finding all the locations in a city. Doing it the other way (Location.joins(:city)) would be for finding what city a location is in.

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

Now, to just find the list of cities that have some locations, you might try City.select(:city).joins(:locations).group('cities.id') The select() clause tells it to just bring back the City, and the group() clause tells it to not bring back duplicate copies.

这篇关于Rails,为什么联接返回具有非唯一值的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆