Browse files

Merge pull request #4942 from bogdan/pluck_joins

AR::Relation#pluck: improve to work with joins

Conflicts:
	activerecord/lib/active_record/relation/calculations.rb
	activerecord/test/cases/calculations_test.rb
  • Loading branch information...
1 parent 1a5caf1 commit a878126028471626a9b30ebe60b7306374fb74ca @josevalim josevalim committed with carlosantoniodasilva Feb 8, 2012
View
4 activerecord/CHANGELOG.md
@@ -1,5 +1,9 @@
## Rails 3.2.10 (unreleased)
+* Fix `pluck` to work with joins. Backport of #4942.
+
+ *Carlos Antonio da Silva*
+
* Fix a problem with `translate_exception` method in a non English environment.
Backport of #6397.
View
7 activerecord/lib/active_record/relation/calculations.rb
@@ -177,7 +177,12 @@ def calculate(operation, column_name, options = {})
# Person.where(:confirmed => true).limit(5).pluck(:id)
#
def pluck(column_name)
- column_name = column_name.to_s
+ if column_name.is_a?(Symbol) && column_names.include?(column_name.to_s)
+ column_name = "#{table_name}.#{column_name}"
+ else
+ column_name = column_name.to_s
+ end
+
relation = clone
relation.select_values = [column_name]
klass.connection.select_all(relation.arel, nil, bind_values).map! do |attributes|
View
10 activerecord/test/cases/calculations_test.rb
@@ -493,4 +493,14 @@ def test_pluck_replaces_select_clause
assert_equal [1,2,3,4], taks_relation.pluck(:id)
assert_equal [false, true, true, true], taks_relation.pluck(:approved)
end
+
+ def test_pluck_auto_table_name_prefix
+ c = Company.create!(:name => "test", :contracts => [Contract.new])
+ assert_equal [c.id], Company.joins(:contracts).pluck(:id)
+ end
+
+ def test_pluck_not_auto_table_name_prefix_if_column_joined
+ c = Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)])
+ assert_equal [7], Company.joins(:contracts).pluck(:developer_id).map(&:to_i)
+ end
end

0 comments on commit a878126

Please sign in to comment.