Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Add ActiveRecord::Base#ids

  • Loading branch information...
commit 93076168c4d2209e007a32abc7142cc23782d56a 1 parent 7d5146e
twinturbo authored
View
10 activerecord/lib/active_record/relation/calculations.rb
@@ -139,6 +139,16 @@ def pluck(column_name)
end
end
+ # Pluck all the ID's for the relation using the table's primary key
+ #
+ # Examples:
+ #
+ # Person.ids # SELECT people.id FROM people
+ # Person.joins(:companies).ids # SELECT people.id FROM PEOPLE INNER JOIN companies ON companies.person_id = people.id
+ def ids
+ pluck primary_key
+ end
+
private
def perform_calculation(operation, column_name, options = {})
View
4 activerecord/test/cases/calculations_test.rb
@@ -465,4 +465,8 @@ def test_pluck_not_auto_table_name_prefix_if_column_joined
Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)])
assert_equal [7], Company.joins(:contracts).pluck(:developer_id)
end
+
+ def test_plucks_with_ids
+ assert_equal Company.all.map(&:id), Company.ids
+ end
end

2 comments on commit 9307616

@Nthalk

Why is this necessary? Isn't hiding calls to all considered bad form?

Also, this prevents me from having a class method of def self.ids(ids); where(id: ids); end that can really dry up my models for batch queries.

@dmathieu
Collaborator

There's no "necessary" or not at this point, since this is a public method which has been around for two years. It can't just be removed.
You can easily solve your issue by using find_by_id though.

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