Skip to content
Browse files

Make ActiveRecord::Relation#pluck work with serialized attributes

  • Loading branch information...
1 parent c1d3e66 commit 16dbe1db1eb0ebf6111d9938b88d1f0652b78734 @jonleighton jonleighton committed Dec 22, 2011
View
8 activerecord/lib/active_record/relation/calculations.rb
@@ -168,7 +168,7 @@ def calculate(operation, column_name, options = {})
# This method is designed to perform select by a single column as direct SQL query
# Returns <tt>Array</tt> with values of the specified column name
- # The values has same data type as column.
+ # The values has same data type as column.
#
# Examples:
#
@@ -177,9 +177,9 @@ def calculate(operation, column_name, options = {})
# Person.where(:confirmed => true).limit(5).pluck(:id)
#
def pluck(column_name)
- scope = self.select(column_name)
- self.connection.select_values(scope.to_sql).map! do |value|
- type_cast_using_column(value, column_for(column_name))
+ column_name = column_name.to_s
+ klass.connection.select_all(select(column_name).arel).map! do |attributes|
+ klass.type_cast_attribute(attributes.keys.first, klass.initialize_attributes(attributes))
end
end
View
9 activerecord/test/cases/calculations_test.rb
@@ -458,7 +458,6 @@ def test_pluck_type_cast
assert_equal [ topic.approved ], relation.pluck(:approved)
assert_equal [ topic.last_read ], relation.pluck(:last_read)
assert_equal [ topic.written_on ], relation.pluck(:written_on)
-
end
def test_pluck_and_uniq
@@ -471,4 +470,12 @@ def test_pluck_in_relation
assert_equal [contract.id], company.contracts.pluck(:id)
end
+ def test_pluck_with_serialization
+ t = Topic.create!(:content => { :foo => :bar })
+ assert_equal [{:foo => :bar}], Topic.where(:id => t.id).pluck(:content)
+ end
+
+ def test_pluck_with_qualified_column_name
+ assert_equal [1,2,3,4], Topic.order(:id).pluck("topics.id")
+ end
end

0 comments on commit 16dbe1d

Please sign in to comment.
Something went wrong with that request. Please try again.