【问题标题】:Query where has_one association is nil查询 has_one 关联为 nil 的位置
【发布时间】:2020-07-06 12:45:34
【问题描述】:

我有一个信息模型:

class Information < ApplicationRecord
  has_one :user, dependent: :restrict_with_exception
end

以及用户模型:

class User < ApplicationRecord
  belongs_to :information, optional: true
end

查询用户在信息中的位置是什么的惯用方法是什么?

我已经试过了,它似乎不起作用:

Information.where(user: nil)

=> []

在我的开发数据库中,我希望它返回 1 条记录,因为我以用户为 nil 的方式设置了一条记录。任何帮助将不胜感激。

【问题讨论】:

  • Information.includes(:user).where(users: {information_id: nil})

标签: ruby-on-rails activerecord


【解决方案1】:

您可以使用它的外键找到它:

Information.where(user_id: nil)

如果您还没有设置外键,您可以通过这种方式创建迁移:

  def change
    add_reference :informations, :users, index: true
  end

PD:我觉得信息应该有belongs_to用户和用户有“has_one”信息的关系。每个用户都有一条“信息”记录对吧?

【讨论】:

    【解决方案2】:

    Information.where('id NOT IN (SELECT DISTINCT(information_id) FROM 用户)')

    【讨论】:

      猜你喜欢
      • 2017-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-10
      相关资源
      最近更新 更多