Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 1 commit into from
Feb 8, 2012
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions activerecord/lib/active_record/relation/calculations.rb
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,9 @@ def calculate(operation, column_name, options = {})
# Person.where(:confirmed => true).limit(5).pluck(:id)
#
def pluck(column_name)
if column_name.is_a?(Symbol) && column_names.include?(column_name.to_s)
column_name = "#{table_name}.#{column_name}"
end
klass.connection.select_all(select(column_name).arel).map! do |attributes|
klass.type_cast_attribute(attributes.keys.first, klass.initialize_attributes(attributes))
end
Expand Down
11 changes: 11 additions & 0 deletions activerecord/test/cases/calculations_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -478,4 +478,15 @@ def test_pluck_with_serialization
def test_pluck_with_qualified_column_name
assert_equal [1,2,3,4], Topic.order(:id).pluck("topics.id")
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)])
# No chance for typecast here
assert_equal ["7"], Company.joins(:contracts).pluck(:developer_id)
end
end