How to unscope joins in RoR 4

645 views Asked by At

Trying to unscope joins.

Example:

class MyModel < ActiveRecord::Base
  default_scope -> { joins("JOIN other_table ON other_table.this_table_id = this_table.id") }
  scope :without_relation -> { unscope(:joins) }
end

The problem is that it unscope ALL joins, even those that are automatically constructed by AR relations.

1

There are 1 answers

0
Vanuan On

Here's what I did:

module UnscopeJoins
  extend ActiveSupport::Concern

  def unscope_joins(joins_string)
    joins_values.reject! {|val| val == joins_string}
    self
  end
end

ActiveRecord::Relation.send :include, UnscopeJoins

Usage:

scope :without_joins, -> { unscope_joins("JOIN table on table2.id = table1.table2_id") }