Skip to content

Instantly share code, notes, and snippets.

@skanev
Last active January 3, 2017 15:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skanev/f23f5f94fa3fbcff4051 to your computer and use it in GitHub Desktop.
Save skanev/f23f5f94fa3fbcff4051 to your computer and use it in GitHub Desktop.
The peculiarities of Relation#distinct and Relation#count
require 'active_record'
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
ActiveRecord::Schema.define do
create_table :activities do |t|
t.string :day
t.string :name
end
end
class Activity < ActiveRecord::Base
end
{
monday: 'running',
tuesday: 'biking',
wednesday: 'swimming',
thursday: 'running',
friday: 'biking',
saturday: nil,
sunday: nil,
}.each do |day, name|
4.times do
Activity.create! day: day, name: name
end
end
relations = {
'select(:name)' => -> { Activity.select(:name) },
'select(:name).distinct' => -> { Activity.select(:name).distinct },
'all' => -> { Activity.all },
'distinct' => -> { Activity.distinct },
'select(:name, :day)' => -> { Activity.select(:day, :name) },
'select(:name, :day).distinct' => -> { Activity.select(:day, :name).distinct }
}
methods = {
'count' => -> (r) { r.count },
'count(:all)' => -> (r) { r.count(:all) },
'size' => -> (r) { r.size },
'to_a.size' => -> (r) { r.to_a.size },
}
print "| %-028s |" % ''
methods.keys.each do |key|
print " %-11s |" % key
end
puts
relations.each do |relation_name, relation|
print "| %-028s |" % relation_name
methods.each do |method_name, method|
begin
print "%12d |" % method.call(relation.call)
rescue
print "%12s |" % '<fail>'
end
end
puts
end
| | count | count(:all) | size | to_a.size |
| select(:name) | 20 | 28 | 28 | 28 |
| select(:name).distinct | 3 | 28 | 28 | 4 |
| all | 28 | 28 | 28 | 28 |
| distinct | 28 | 28 | 28 | 28 |
| select(:name, :day) | <fail> | 28 | 28 | 28 |
| select(:name, :day).distinct | <fail> | 28 | 28 | 7 |
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment