ruby笔记(四)


rails关联查询

单个关联

1
Client.includes(:address).limit(10)

多个关联

1
Article.includes(:category, :comments)

嵌套关联散列

1
Category.includes(articles: [{ comments: :guest }, :tags])

关联查询 为关联指明条件

1
Article.includes(:comments).where(comments: { visible: true })

上面的代码会生成使用 LEFT OUTER JOIN 子句的 SQL 语句,而 joins 方法会成生使用 INNER JOIN 子句的 SQL 语句。

1
SELECT "articles"."id" AS t0_r0, ... "comments"."updated_at" AS t1_r5 FROM "articles" LEFT OUTER JOIN "comments" ON "comments"."article_id" = "articles"."id" WHERE (comments.visible = 1)