使用连接的 Ruby on Rails ActiveRecord 查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10391266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby on Rails ActiveRecord query using a join
提问by randombits
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"
我有一个 User 模型,用户有一个关系是 has_many pets。我希望能够编写一个 ActiveRecord 查询,在其中我可以选择所有用户的宠物没有“fluffy”的 pet.name
What's the most efficient way to write this using ActiveRecord? Using straight SQL it would look something such as the following:
使用 ActiveRecord 编写此文件的最有效方法是什么?使用直接的 SQL,它看起来像下面这样:
select id from users INNER JOIN pets ON u.id = pets.user_id WHERE pets.name != "fluffy"
select id from users INNER JOIN pets ON u.id = pets.user_id WHERE pets.name != "fluffy"
回答by Amokrane Chentir
This should work:
这应该有效:
User.joins(:pets).where("pets.name != 'fluffy'")
Also you might want to read the following part(on joins) on the official RoR guidelines.
此外,您可能还想阅读有关官方 RoR 指南的以下部分(关于joins)。
回答by Albin
In rails 4 you can make this even more clear:
在 rails 4 中,您可以更清楚地说明这一点:
User.joins(:pets).where.not(pets: { name: 'fluffy' })
回答by gertas
The cleanest way without SQL injection vulnerability is using query parameters:
没有 SQL 注入漏洞的最干净的方法是使用查询参数:
User.joins(:pets).where("pets.name != ?", "fluffy")
Some database drivers will utilize prepared statements for above to reuse database query plan. In such case the database doesn't have to analyze query again when only param value varies.
一些数据库驱动程序将利用上述准备好的语句来重用数据库查询计划。在这种情况下,当只有参数值变化时,数据库不必再次分析查询。

