Skip to content

Commit 4b91daf

Browse files
committed
Special treatement for Relation#select { with block }
1 parent 0570720 commit 4b91daf

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

activerecord/lib/active_record/relation/query_methods.rb

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ module QueryMethods
99
(ActiveRecord::Relation::ASSOCIATION_METHODS + ActiveRecord::Relation::MULTI_VALUE_METHODS).each do |query_method|
1010
attr_accessor :"#{query_method}_values"
1111

12-
next if [:where, :having].include?(query_method)
12+
next if [:where, :having, :select].include?(query_method)
1313
class_eval <<-CEVAL, __FILE__, __LINE__ + 1
1414
def #{query_method}(*args, &block)
1515
new_relation = clone
@@ -21,6 +21,19 @@ def #{query_method}(*args, &block)
2121
CEVAL
2222
end
2323

24+
class_eval <<-CEVAL, __FILE__, __LINE__ + 1
25+
def select(*args, &block)
26+
if block_given?
27+
to_a.select(&block)
28+
else
29+
new_relation = clone
30+
value = Array.wrap(args.flatten).reject {|x| x.blank? }
31+
new_relation.select_values += value if value.present?
32+
new_relation
33+
end
34+
end
35+
CEVAL
36+
2437
[:where, :having].each do |query_method|
2538
class_eval <<-CEVAL, __FILE__, __LINE__ + 1
2639
def #{query_method}(*args, &block)

activerecord/test/cases/relations_test.rb

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,11 @@ def test_finding_with_group
112112
assert_equal 4, developers.map(&:salary).uniq.size
113113
end
114114

115+
def test_select_with_block
116+
even_ids = Developer.scoped.select {|d| d.id % 2 == 0 }.map(&:id)
117+
assert_equal [2, 4, 6, 8, 10], even_ids
118+
end
119+
115120
def test_finding_with_hash_conditions_on_joined_table
116121
firms = DependentFirm.joins(:account).where({:name => 'RailsCore', :accounts => { :credit_limit => 55..60 }}).to_a
117122
assert_equal 1, firms.size

0 commit comments

Comments
 (0)