使用连接的 Ruby on Rails ActiveRecord 查询

编程入门 行业动态 更新时间:2024-10-27 05:23:56
本文介绍了使用连接的 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 查询

本文发布于:2023-10-22 08:10:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1516949.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Ruby   Rails   ActiveRecord

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!