我有一个 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 查询
发布评论