Searching through Table connections in Rails
Suppose I have two tables, one called zombies (id, name, gra开发者_运维知识库veyard), and one called weapons (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'?
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.
So in conclusion: includes will do a join, but also keep around the table included so you can reference it in the where clause.
精彩评论