kovpack
kovpack

Reputation: 5045

Get deleted object with paranoid through related activerecord objects

I have 3 models:

class Request < ActiveRecord::Base
  acts_as_paranoid
  belongs_to :offer
end

class Offer < ActiveRecord::Base
  belongs_to :cruise, inverse_of: :offers
  has_many :requests
end

class Travel < ActiveRecord::Base
  acts_as_paranoid    
  has_many :offers, inverse_of: :travel
end

Usually I can access Travel object through chain like this: request.offer.travel.

However, if Travel object I need is deleted with paranoia - I can not access it through such objects chain.

Travel.with_deleted.find(some_id_of_deleted_travel) works perfectly, but request.offers.travel.with_deleted, that the same object, throws me undefined method 'with_deleted' for nil:NilClass.

How can I access deleted object through relation?

Upvotes: 3

Views: 2473

Answers (2)

eveevans
eveevans

Reputation: 4460

On Rails > 4. You can use the unscope method for remove the paranoid scope.

class Request < ActiveRecord::Base
  acts_as_paranoid
  belongs_to :offer, -> { unscope(where: :deleted_at) }
end

Upvotes: 1

kovpack
kovpack

Reputation: 5045

I've found the answer, however, I'm not satisfied with it.

It order to get associated object that was soft deleted, I have to modify Offer model like this and unscope relation:

class Offer < ActiveRecord::Base
  belongs_to :cruise, inverse_of: :offers
  has_many :requests

  def travel
    Travel.unscoped { super }
  end
end

In my case this works, but breaks some functionality, cause I need to unscope relation only in this very situation, leaving other cases untouched. It would be nice to have something like request.offers.travel(:unscoped) etc.

In my case best solution was simply access this object separately like Travel.with_deleted.find(@offer.travel_id)

Upvotes: 4

Related Questions