Permalink
Browse files

Support updates with joins. Fixes #522.

Conflicts:

	activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
	activerecord/test/cases/relations_test.rb
  • Loading branch information...
1 parent e749abc commit 044fb8c3e2bf1ec27602e52f6a70ba3b3f5da310 @jonleighton jonleighton committed Aug 8, 2011
@@ -333,6 +333,15 @@ def sanitize_limit(limit)
end
end
+ # The default strategy for an UPDATE with joins is to use a subquery. This doesn't work
+ # on mysql (even when aliasing the tables), but mysql allows using JOIN directly in
+ # an UPDATE statement, so in the mysql adapters we redefine this to do that.
+ def join_to_update(update, select) #:nodoc:
+ subselect = select.clone
+ subselect.ast.cores.last.projections = [update.ast.key]
+ update.wheres = [update.ast.key.in(subselect)]
+ end
+
protected
# Returns an array of record hashes with the column names as keys and
# column values as values.
@@ -599,6 +599,10 @@ def limited_update_conditions(where_sql, quoted_table_name, quoted_primary_key)
where_sql
end
+ def join_to_update(update, select) #:nodoc:
+ update.table select.ast.cores.last.source
+ end
+
protected
def quoted_columns_for_index(column_names, options = {})
length = options[:length] if options.is_a?(Hash)
@@ -505,6 +505,10 @@ def add_limit_offset!(sql, options) #:nodoc:
end
deprecate :add_limit_offset!
+ def join_to_update(update, select) #:nodoc:
+ update.table select.ast.cores.last.source
+ end
+
# SCHEMA STATEMENTS ========================================
def structure_dump #:nodoc:
@@ -217,13 +217,18 @@ def update_all(updates, conditions = nil, options = {})
where(conditions).apply_finder_options(options.slice(:limit, :order)).update_all(updates)
else
stmt = arel.compile_update(Arel.sql(@klass.send(:sanitize_sql_for_assignment, updates)))
+ stmt.key = table[primary_key]
- if limit = arel.limit
- stmt.take limit
+ if joins_values.any?
+ @klass.connection.join_to_update(stmt, arel)
+ else
+ if limit = arel.limit
+ stmt.take limit
+ end
+
+ stmt.order(*arel.orders)
end
- stmt.order(*arel.orders)
- stmt.key = table[primary_key]
@klass.connection.update stmt, 'SQL', bind_values
end
end
@@ -952,4 +952,12 @@ def test_eager_loading_with_conditions_on_joins
assert scope.eager_loading?
end
+
+ def test_update_all_with_joins
+ comments = Comment.joins(:post).where('posts.id' => posts(:welcome).id)
+ count = comments.count
+
+ assert_equal count, comments.update_all(:post_id => posts(:thinking).id)
+ assert_equal posts(:thinking), comments(:greetings).post
+ end
end

0 comments on commit 044fb8c

Please sign in to comment.