使用联接的Ruby on Rails ActiveRecord查询 [英] Ruby on Rails ActiveRecord query using a join

查看:63
本文介绍了使用联接的Ruby on Rails ActiveRecord查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户模型,该用户具有has_many pets的关系。我希望能够编写一个ActiveRecord查询,在其中可以选择所有拥有不带pet的宠物的用户。名称为蓬松

I have a User model and the user has a relationship which is has_many pets. I want to be able to write an ActiveRecord query where I can select all users with a pet that doesn't have a pet.name of "fluffy"

什么是最ActiveRecord编写此有效的方法?使用简单的SQL看起来像以下内容:

What's the most efficient way to write this using ActiveRecord? Using straight SQL it would look something such as the following:

从用户中选择ID INNER JOIN pets on u.id = pets.user_id WHERE pets .name!=蓬松

推荐答案

这应该有效:

User.joins(:pets).where("pets.name != 'fluffy'")

另外,您可能需要阅读下一部分(在 joins 上),遵循官方RoR指南。

Also you might want to read the following part (on joins) on the official RoR guidelines.

这篇关于使用联接的Ruby on Rails ActiveRecord查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆