Ruby on Rails ActiveRecord query using a join

前端 未结 3 837
独厮守ぢ
独厮守ぢ 2020-12-28 12:15

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 doe

相关标签:
3条回答
  • 2020-12-28 12:53

    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.

    0 讨论(0)
  • 2020-12-28 12:58

    The cleanest way without SQL injection vulnerability is using query parameters:

    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.

    0 讨论(0)
  • 2020-12-28 13:02

    In rails 4 you can make this even more clear:

    User.joins(:pets).where.not(pets: { name: 'fluffy' })
    
    0 讨论(0)
提交回复
热议问题