Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Paranoia Gem - joins with deleted items

I'm using Paranoia gem and now struggling with the problem. I need to joins has_many deleted items, but it returns not deleted only. My models:

class Mailing < ActiveRecord::Base

  acts_as_paranoid

  has_many :mailing_fields
  has_many :fields, through: :mailing_fields

end

class MailingField < ActiveRecord::

  belongs_to :mailing
  belongs_to :field

end

class Field < ActiveRecord::Base

  has_many :mailing_fields, dependent: :destroy
  has_many :mailings, through: :mailing_fields

end

Query I'm running which should return mailings with deleted items:

Field.joins(:mailings).where('mailings.id = ?', mailing_id)
like image 264
Pavel Babin Avatar asked Aug 14 '16 20:08

Pavel Babin


People also ask

How do I access deleted items in paranoid?

Paranoid gem has built-in scope to access deleted items: with_deleted. Mailing.with_deleted.joins (:fields).where (id: mailing_id) This is insufficient if the parent MailingField object to the Field object is also deleted.

How do you destroy an object in paranoia?

Paranoia does this by setting a deleted_at field to the current time when you destroy a record, and hides it by scoping all queries on your model to only include records which do not have a deleted_at field. If you wish to actually destroy an object you may call really_destroy!.

How does paranoia work with ActiveRecord destroy?

When your app is using Paranoia, calling destroy on an ActiveRecord object doesn't actually destroy the database record, but just hides it. Paranoia does this by setting a deleted_at field to the current time when you destroy a record, and hides it by scoping all queries on your model to only include records which do not have a deleted_at field.

What is paranoia in rails?

Paranoia is a re-implementation of acts_as_paranoid for Rails 3/4/5, using much, much, much less code. When your app is using Paranoia, calling destroy on an ActiveRecord object doesn't actually destroy the database record, but just hides it.


1 Answers

The only working solution I've found so far is to manually specify the JOIN:

Field.joins('INNER JOIN "mailings" ON "mailings"."id" = "fields"."mailing_id"')
     .where('mailings.id = ?', mailing_id)
like image 179
Fabian Winkler Avatar answered Sep 18 '22 06:09

Fabian Winkler