试图取消连接范围。
例子:
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
问题是它取消了所有连接的范围,即使是那些由 AR 关系自动构建的连接。
试图取消连接范围。
例子:
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
问题是它取消了所有连接的范围,即使是那些由 AR 关系自动构建的连接。
这是我所做的:
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
用法:
scope :without_joins, -> { unscope_joins("JOIN table on table2.id = table1.table2_id") }