Skip to content

Instantly share code, notes, and snippets.

@iamvery
Last active August 29, 2015 14:06
Show Gist options
  • Save iamvery/9563c7eb23f00ecac0e0 to your computer and use it in GitHub Desktop.
Save iamvery/9563c7eb23f00ecac0e0 to your computer and use it in GitHub Desktop.

An example of finding records with no associated record.

● master ~/Code/OSS/no-associated » bundle console
irb(main):002:0> require_relative 'dog'
=> true
irb(main):003:0> require_relative 'owner'
=> true
irb(main):004:0> Owner.create!
=> #<Owner id: 1, dog_id: nil>
irb(main):005:0> _.create_dog!
=> #<Dog id: 1>
irb(main):006:0> Dog.create!
=> #<Dog id: 2>
irb(main):007:0> Dog.all
=> #<ActiveRecord::Relation [#<Dog id: 1>, #<Dog id: 2>]>
irb(main):008:0> Dog.includes(:owner).where(owners: { id: nil })
=> #<ActiveRecord::Relation [#<Dog id: 2>]>
irb(main):009:0> Dog.includes(:owner).where(owners: { id: nil }).to_sql
=> "SELECT \"dogs\".\"id\" AS t0_r0, \"owners\".\"id\" AS t1_r0, \"owners\".\"dog_id\" AS t1_r1 FROM \"dogs\" LEFT OUTER JOIN \"owners\" ON \"owners\".\"dog_id\" = \"dogs\".\"id\" WHERE \"owners\".\"id\" IS NULL"
require 'active_record'
ActiveRecord::Base.establish_connection adapter: 'sqlite3', database: ':memory:'
ActiveRecord::Base.connection.create_table :dogs
ActiveRecord::Base.connection.create_table :owners do |t|
t.belongs_to :dog
end
require_relative 'db'
class Dog < ActiveRecord::Base
has_one :owner
end
source 'https://rubygems.org'
gem 'activerecord'
gem 'sqlite3'
GEM
remote: https://rubygems.org/
specs:
activemodel (4.1.6)
activesupport (= 4.1.6)
builder (~> 3.1)
activerecord (4.1.6)
activemodel (= 4.1.6)
activesupport (= 4.1.6)
arel (~> 5.0.0)
activesupport (4.1.6)
i18n (~> 0.6, >= 0.6.9)
json (~> 1.7, >= 1.7.7)
minitest (~> 5.1)
thread_safe (~> 0.1)
tzinfo (~> 1.1)
arel (5.0.1.20140414130214)
builder (3.2.2)
i18n (0.6.11)
json (1.8.1)
minitest (5.4.1)
sqlite3 (1.3.9)
thread_safe (0.3.4)
tzinfo (1.2.2)
thread_safe (~> 0.1)
PLATFORMS
ruby
DEPENDENCIES
activerecord
sqlite3
require_relative 'db'
class Owner < ActiveRecord::Base
belongs_to :dog
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment