查询has_one关联为nil的位置

时间:2020-07-06 12:45:34

标签: ruby-on-rails activerecord

我有一个信息模型:

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

用户模型:

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

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

我已经尝试过了,但似乎没有用:

Information.where(user: nil)

=> []

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

2 个答案:

答案 0 :(得分:0)

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

Information.where(user_id: nil)

如果尚未设置外键,则可以通过以下方式创建迁移:

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

PD:我觉得应该具有属于用户的信息和具有“ has_one”信息的用户之间的关系。每个用户都有一条“信息”记录吗?

答案 1 :(得分:0)

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