Skip to content
This repository
Browse code

Make ActiveRecord::Relation#pluck work with serialized attributes

  • Loading branch information...
commit 16dbe1db1eb0ebf6111d9938b88d1f0652b78734 1 parent c1d3e66
Jon Leighton jonleighton authored
8 activerecord/lib/active_record/relation/calculations.rb
@@ -168,7 +168,7 @@ def calculate(operation, column_name, options = {})
168 168
169 169 # This method is designed to perform select by a single column as direct SQL query
170 170 # Returns <tt>Array</tt> with values of the specified column name
171   - # The values has same data type as column.
  171 + # The values has same data type as column.
172 172 #
173 173 # Examples:
174 174 #
@@ -177,9 +177,9 @@ def calculate(operation, column_name, options = {})
177 177 # Person.where(:confirmed => true).limit(5).pluck(:id)
178 178 #
179 179 def pluck(column_name)
180   - scope = self.select(column_name)
181   - self.connection.select_values(scope.to_sql).map! do |value|
182   - type_cast_using_column(value, column_for(column_name))
  180 + column_name = column_name.to_s
  181 + klass.connection.select_all(select(column_name).arel).map! do |attributes|
  182 + klass.type_cast_attribute(attributes.keys.first, klass.initialize_attributes(attributes))
183 183 end
184 184 end
185 185
9 activerecord/test/cases/calculations_test.rb
@@ -458,7 +458,6 @@ def test_pluck_type_cast
458 458 assert_equal [ topic.approved ], relation.pluck(:approved)
459 459 assert_equal [ topic.last_read ], relation.pluck(:last_read)
460 460 assert_equal [ topic.written_on ], relation.pluck(:written_on)
461   -
462 461 end
463 462
464 463 def test_pluck_and_uniq
@@ -471,4 +470,12 @@ def test_pluck_in_relation
471 470 assert_equal [contract.id], company.contracts.pluck(:id)
472 471 end
473 472
  473 + def test_pluck_with_serialization
  474 + t = Topic.create!(:content => { :foo => :bar })
  475 + assert_equal [{:foo => :bar}], Topic.where(:id => t.id).pluck(:content)
  476 + end
  477 +
  478 + def test_pluck_with_qualified_column_name
  479 + assert_equal [1,2,3,4], Topic.order(:id).pluck("topics.id")
  480 + end
474 481 end

0 comments on commit 16dbe1d

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