Rails联接查询 [英] Rails joins query
本文介绍了Rails联接查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有三个模型
-
标签
=>:id
,:name
-
标记
=>:id
,:tag_id
,:post_id
-
Post
=>:id
,:摘要
Tag
=>:id
,:name
Tagging
=>:id
,:tag_id
,:post_id
Post
=>:id
,:summary
我知道标签的ID。我想通过 Taggings
模型查询所有具有特定 tag_id
的帖子。
I know the id of the tag. I would like to query for all of the posts that have a specific tag_id
, through the Taggings
model.
类似
@post = Post.joins(:taggings).where(:tag_id => 17)
但这不起作用,因为它正在寻找tag_id在 Post
模型中,而不在 Tagging
模型中。
but this doesn't work because it is looking for the tag_id in the Post
model and not the Tagging
model.
我不确定该怎么做。
推荐答案
使用.where格式,您可以传递.where( taggings.tag_id =?,17)之类的字符串来限定联接的标签表。
Using the .where format you can pass a string like .where("taggings.tag_id = ?", 17) to qualify the joined taggings table.
这篇关于Rails联接查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文