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

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

问题描述

我有一个 User 模型,用户有一个关系是 has_many pets.我希望能够编写一个 ActiveRecord 查询,我可以在其中选择所有用户的宠物没有蓬松"的 pet.name

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:

select id from users INNER JOIN pets ON u.id = pets.user_id WHERE pets.name != "fluffy"

推荐答案

这应该有效:

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天全站免登陆