Finding nil has_one associations in where query

后端 未结 3 1733
栀梦
栀梦 2020-12-23 13:57

This may be a simple question, but I seem to be pulling my hair out to find an elegant solution here. I have two ActiveRecord model classes, with a has_one and belongs_to as

相关标签:
3条回答
  • 2020-12-23 14:22

    A more concise version of @dimuch solution is to use the left_outer_joins method introduced in Rails 5:

    Item.left_outer_joins(:purchase).where(purchases: {id: nil})
    

    Note that in the left_outer_joins call :purchase is singular (it is the name of the method created by the has_one declaration), and in the where clause :purchases is plural (here it is the name of the table that the id field belongs to.)

    0 讨论(0)
  • 2020-12-23 14:42

    It's quite common task, SQL OUTER JOIN usually works fine for it. Take a look here, for example.

    In you case try to use something like

    not_purchased_items = Item.joins("LEFT OUTER JOIN purchases ON purchases.item_id = items.id").where("purchases.id IS null")
    
    0 讨论(0)
  • 2020-12-23 14:48

    Found two other railsey ways of doing this:

    Item.includes(:purchase).references(:purchase).where("purchases.id IS NULL")
    
    Item.includes(:purchase).where(purchases: { id: nil })
    

    Technically the first example works without the 'references' clause but Rails 4 spits deprecation warnings without it.

    0 讨论(0)
提交回复
热议问题