Nick ONeill
Nick ONeill

Reputation: 7379

How to query a self-referencing has_one relationship

I have the following model:

class PropertyType < ApplicationRecord
  has_one :parent, :class_name => "PropertyType"
  has_and_belongs_to_many :properties
end

It can have a parent of it's own class type. However none of the following queries appear to work:

PropertyType.where("property_type_id IS NULL")
PropertyType.where(parent: nil)

What am I missing here?

Upvotes: 1

Views: 243

Answers (1)

Anthony E
Anthony E

Reputation: 11235

I think you might want a :belongs_to rather than a :has_one. You may want to also consider using naming foreign key so the direction of the relationship is more clear. In this case you would need to explicitly specify the foreign key:

class ProjectType
 belongs_to :parent, class_name: "ProjectType", foreign_key: :parent_project_type_id
 has_many :children, class_name: "ProjectType", foreign_key: :parent_project_type_id

 # ...
end

Upvotes: 1

Related Questions