我在 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
关联就会丢失。
这种行为是预期的吗?它是否记录在我无法找到的某个地方?
谢谢!