加盟
joins()
允许你将表连接到当前模型。对于前者
User.joins(:posts)
将生成以下 SQL 查询:
"SELECT "users".* FROM "users" INNER JOIN "posts" ON "posts"."user_id" = "users"."id""
加入表后,你将可以访问它:
User.joins(:posts).where(posts: { title: "Hello world" })
注意复数形式。如果你的关系是:has_many
,则 joins()
参数应该是复数。否则,使用单数。
嵌套 joins
:
User.joins(posts: :images).where(images: { caption: 'First post' })
这将产生:
"SELECT "users".* FROM "users" INNER JOIN "posts" ON "posts"."user_id" = "users"."id" INNER JOIN "images" ON "images"."post_id" = "images"."id""