Questions for presence/absence validations

Hello, I have some questions for Validation Guides:

If you want to be sure that an association is present, you’ll need to test whether the associated object itself is present, and not the foreign key used to map the association. This way, it is not only checked that the foreign key is not empty but also that the referenced object exists.

class Supplier < ApplicationRecord
  has_one :account
  validates :account, presence: true
end

In order to validate associated records whose presence is required, you must specify the :inverse_of option for the association:

class Order < ApplicationRecord
  has_many :line_items, inverse_of: :order
end

Q1: It seems that the Order and ListItem models above are not relevant to the Supplier model, and this might confuse us. I wonder where does line_items come from.

I suppose the Order model can be revised to Account model to correspond with the Supplier model, as the description for absence below does:

If you want to be sure that an association is absent, you’ll need to test whether the associated object itself is absent, and not the foreign key used to map the association.

class LineItem < ApplicationRecord
  belongs_to :order
  validates :order, absence: true
end

In order to validate associated records whose absence is required, you must specify the :inverse_of option for the association:

class Order < ApplicationRecord
  has_many :line_items, inverse_of: :order
end

Q2: As far as I examined with the following models based on the samples above, the inverse_of: option should be added to has_many :line_items instead of adding to belongs_to :order, to make presence: true option work. I’m unsure if I misunderstood something…

# works as expected: `Order.new(order: "foo").valid?` is `false`
  class LineItem < ApplicationRecord
    belongs_to :order
  end

  class Order < ApplicationRecord
    has_many :line_items, inverse_of: :order
    validates :line_items, presence: true
  end
# does not work as expected: `Order.new(order: "foo").valid?` is `true` 
  class LineItem < ApplicationRecord
    belongs_to :order
    validates :order, presence: true
  end

  class Order < ApplicationRecord
    has_many :line_items, inverse_of: :order
  end

Best regards,

1 Like

Hi @hachi8833! We currently have a PR up to update this guide. Can you please check to see if your edits are already reflected there? [RF-DOCS]Active Record Validations [ci skip] by Ridhwana · Pull Request #52951 · rails/rails · GitHub

If not, feel free to submit a review to suggest that change. Thank you in advance!

1 Like

Oh, thank you! I’ll look into it soon.