Skip to content

Commit

Permalink
Merge pull request #8994 from Springest/fix_default_scope_update_all_…
Browse files Browse the repository at this point in the history
…delete_all

Fix .update_all and .delete_all when using a condition on a joined table in a default_scope
  • Loading branch information
jonleighton committed Jan 18, 2013
2 parents 1d55e07 + bc4edca commit 40e7978
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 2 deletions.
4 changes: 2 additions & 2 deletions activerecord/lib/active_record/relation.rb
Expand Up @@ -276,7 +276,7 @@ def update_all(updates)
stmt.table(table)
stmt.key = table[primary_key]

if joins_values.any?
if with_default_scope.joins_values.any?
@klass.connection.join_to_update(stmt, arel)
else
stmt.take(arel.limit)
Expand Down Expand Up @@ -401,7 +401,7 @@ def delete_all(conditions = nil)
stmt = Arel::DeleteManager.new(arel.engine)
stmt.from(table)

if joins_values.any?
if with_default_scope.joins_values.any?
@klass.connection.join_to_delete(stmt, arel, table[primary_key])
else
stmt.wheres = arel.constraints
Expand Down
22 changes: 22 additions & 0 deletions activerecord/test/cases/relation_scoping_test.rb
Expand Up @@ -161,6 +161,28 @@ def test_ensure_that_method_scoping_is_correctly_restored

assert !Developer.all.where_values.include?("name = 'Jamis'")
end

def test_default_scope_filters_on_joins
assert_equal 1, DeveloperFilteredOnJoins.all.count
assert_equal DeveloperFilteredOnJoins.all.first, developers(:david).becomes(DeveloperFilteredOnJoins)
end

def test_update_all_default_scope_filters_on_joins
DeveloperFilteredOnJoins.update_all(:salary => 65000)
assert_equal 65000, Developer.find(developers(:david).id).salary

# has not changed jamis
assert_not_equal 65000, Developer.find(developers(:jamis).id).salary
end

def test_delete_all_default_scope_filters_on_joins
assert_not_equal [], DeveloperFilteredOnJoins.all

DeveloperFilteredOnJoins.delete_all()

assert_equal [], DeveloperFilteredOnJoins.all
assert_not_equal [], Developer.all
end
end

class NestedRelationScopingTest < ActiveRecord::TestCase
Expand Down
9 changes: 9 additions & 0 deletions activerecord/test/models/developer.rb
Expand Up @@ -101,6 +101,15 @@ class DeveloperWithIncludes < ActiveRecord::Base
default_scope { includes(:audit_logs) }
end

class DeveloperFilteredOnJoins < ActiveRecord::Base
self.table_name = 'developers'
has_and_belongs_to_many :projects, -> { order('projects.id') }, :foreign_key => 'developer_id', :join_table => 'developers_projects'

def self.default_scope
joins(:projects).where(:projects => { :name => 'Active Controller' })
end
end

class DeveloperOrderedBySalary < ActiveRecord::Base
self.table_name = 'developers'
default_scope { order('salary DESC') }
Expand Down

0 comments on commit 40e7978

Please sign in to comment.