0

我在 Rails 中遇到了这种我在文档中似乎找不到的行为。

看来,如果您将 ActiveRecord 查询复杂化到将底层 SQL 集中到“复杂”查询中(见下文),则它不遵守关联中指定的排序。

这是我的示例模型:

class Article < ActiveRecord::Base
  belongs_to :user
  has_many :categories, :order => :name
  attr_accessible :title, :user_id, :user
end

如果我执行“简单”查询,我可以获得按名称排序的关联类别:

> Article.includes(:categories).first.categories.map &:name
  Article Load (0.1ms)  SELECT "articles".* FROM "articles" LIMIT 1
  Category Load (0.2ms)  SELECT "categories".* FROM "categories" WHERE "categories"."article_id" IN (11) ORDER BY name
 => ["category 3059", "category 3212", "category 3240", "category 3651", "category 4371", "category 5243", "category 6176", "category 6235", "category 6468", "category 654", "category 6804", "category 6892", "category 7026", "category 8929", "category 9653"]

您可以看到类别的名称按预期顺序排列(注意:由于数据库对字符串的排序方式,我希望 3 位数编号的类别按字母顺序排列)。

下一个示例是一个更复杂的查询,使用另一个关联属性进行排序:

> Article.includes(:user, :categories).order('users.name').first.categories.map &:name
  Article Load (0.3ms)  SELECT DISTINCT "articles".id FROM "articles" LEFT OUTER JOIN "users" ON "users"."id" = "articles"."user_id" LEFT OUTER JOIN "categories" ON "categories"."article_id" = "articles"."id" ORDER BY users.name LIMIT 1
  SQL (0.2ms)  SELECT "articles"."id" AS t0_r0, "articles"."title" AS t0_r1, "articles"."user_id" AS t0_r2, "articles"."created_at" AS t0_r3, "articles"."updated_at" AS t0_r4, "users"."id" AS t1_r0, "users"."name" AS t1_r1, "users"."created_at" AS t1_r2, "users"."updated_at" AS t1_r3, "categories"."id" AS t2_r0, "categories"."name" AS t2_r1, "categories"."article_id" AS t2_r2, "categories"."created_at" AS t2_r3, "categories"."updated_at" AS t2_r4 FROM "articles" LEFT OUTER JOIN "users" ON "users"."id" = "articles"."user_id" LEFT OUTER JOIN "categories" ON "categories"."article_id" = "articles"."id" WHERE "articles"."id" IN (16) ORDER BY users.name
 => ["category 5023", "category 728", "category 3306", "category 8170", "category 5957", "category 7190", "category 4427", "category 3435", "category 1274", "category 7251", "category 7368", "category 682", "category 2918"]

如您所见,当 AR 将查询集中到其“复杂”SQL 查询之一时,categories关联就会丢失。

这种行为是预期的吗?它是否记录在我无法找到的某个地方?

谢谢!

4

1 回答 1

3

这里的问题是:您正在执行连接并通过“users.name”对其进行排序。

当您进行连接时,您将 2 个表放在一起,任何排序都会影响整个连接表。

由于您无论如何都要进行 2 个查询,所以我会这样写:

Article.includes(:user, :categories).order('users.name').first.categories.order(:name).map &:name

或者更好的是,使用采摘方法。它只返回一列值:

Article.includes(:user, :categories).order('users.name').first.categories.order(:name).pluck(:name)

这样您就不必加载所有类别属性来列出它们的名称。=)

PS:

如果要进行双重排序,可以将两个参数传递给 order:

Article.includes(:user, :categories).order('users.name', 'categories.name')

我没有写整个查询,因为我不明白你到底想恢复什么。如果你解释得更多,我可以试一试。到目前为止,我了解到您正在尝试获取属于第一个用户的文章的所有类别,按名称排序,按名称排序。但对我来说,如果没有上下文,这个查询没有多大意义。

于 2012-08-22T15:55:12.197 回答