简体   繁体   English

在 Rails 中搜索表连接

[英]Searching through Table connections in Rails

Suppose I have two tables, one called zombies (id, name, graveyard), and one called weapons (id, name, strength, zombie_id).假设我有两张桌子,一张叫僵尸(id,name,graveyard),一张叫武器(id,name,strength,zombie_id)。 Weapons:belongs_to Zombies What's the easiest way to find the weapon that has a zombie of name 'jack'? Weapons:belongs_to Zombies 找到拥有名为“jack”的僵尸的武器的最简单方法是什么?

Thanks!谢谢!

Weapon.includes(:zombie).where("zombies.name = ?", "jack")

This will return a collection, so if you want just the first, append .first to that query.这将返回一个集合,所以如果你只想要第一个, .first .first 到那个查询。

So in conclusion: includes will do a join, but also keep around the table included so you can reference it in the where clause.总而言之:includes 会进行连接,但也会保留包含的表,以便您可以在 where 子句中引用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM