Skip to content

Instantly share code, notes, and snippets.

@mrkn
Created January 30, 2014 15:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrkn/8711146 to your computer and use it in GitHub Desktop.
Save mrkn/8711146 to your computer and use it in GitHub Desktop.
require 'active_record'
ActiveRecord::Base.establish_connection(
adapter: 'sqlite3',
database: 'test',
)
class Migration < ActiveRecord::Migration
def up
drop_table :users rescue nil
create_table :users do |t|
t.integer :age
end
drop_table :foos rescue nil
create_table :foos do |t|
t.integer :user_id
end
end
end
Migration.new.up
class User < ActiveRecord::Base
has_many :foos
end
class Foo < ActiveRecord::Base
belongs_to :user
end
users = 100.times.map { User.create(age: rand(100)) }
foos = 1000.times.map { Foo.create(user: users.sample) }
ActiveRecord::Base.logger = Logger.new $stdout
p Foo.joins(:user).where(user_id: User.where('users.age % 3 = 0')).group(:user_id).count
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment