Skip to content

Issue preloading soft deleted records #672

@jwoertink

Description

@jwoertink

I'll need to investigate this more, but we just ran in to an issue with some preloads.

Take this model setup

class User < BaseModel
  table do
    # ...
    column soft_deleted_at : Time?
    has_many transactions : Transaction
  end
end

class Transaction < BaseModel
  table do
    belongs_to user : User
  end
end

class User::BaseQuery
  include Avram::SoftDelete::Query

  def initialize
    defaults &.only_kept
  end
end

class UserQuery < User::BaseQuery
end

class TransactionQuery < Transaction::BaseQuery
end

Then we had some code like this:

# in the action
transactions = TransactionQuery.new.preload_user

# in the page

transactions.each do |transaction|
  td do
    link(transaction.user.username, to: Users::Show.with(transaction.user_id))
  end
end

We kept getting a 500 error saying NilAssertionError which generally relates to calling not_nil! somewhere. In this case, our user should never be nil, but calling transaction.user says otherwise. We printed out the record, and saw this:

#<Transaction:0x7f9cdd05a8f0 @_user_preloaded=true, @_preloaded_user=nil, @id=1, @created_at=2021-04-28 18:02:47.0 UTC, @updated_at=2021-04-28 18:02:47.0 UTC, @user_id=4>

Looking up user 4, we saw the record existed, but it was soft deleted.

Avram should probably log some sort of warning that a required record could not be preloaded, or maybe when you preload an association that's been soft deleted, that record isn't returned at all?

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions