Skip to content

Instantly share code, notes, and snippets.

@nishantmodak
Created December 27, 2013 13:57
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 nishantmodak/8147200 to your computer and use it in GitHub Desktop.
Save nishantmodak/8147200 to your computer and use it in GitHub Desktop.
unless File.exist?('Gemfile')
File.write('Gemfile', <<-GEMFILE)
source 'https://rubygems.org'
gem 'rails'
gem 'arel'
gem 'sqlite3'
gem 'minitest'
GEMFILE
system 'bundle'
end
require 'bundler'
Bundler.setup(:default)
require 'active_record'
require 'minitest/autorun'
require 'logger'
# This connection will do for database-independent bug reports.
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table :blogs do |t|
t.string :name
t.timestamps
end
create_table :posts do |t|
t.string :title
t.references :blog
t.timestamps
end
create_table :comments do |t|
t.string :comment
t.references :post
t.timestamps
end
end
class Blog < ActiveRecord::Base
has_many :posts, dependent: :destroy
has_many :comments, through: :posts, dependent: :destroy
end
class Post < ActiveRecord::Base
belongs_to :blog
has_many :comments, dependent: :destroy
end
class Comment < ActiveRecord::Base
belongs_to :post
end
class BugTest < Minitest::Test
def test_association_stuff
blog = Blog.create!
blog.posts << Post.create!
blog.posts.first.comments << Comment.create!
assert_equal 1, blog.posts.first.comments.count
assert_equal 1, Comment.count
assert_equal blog.posts.first.id, Comment.first.post.id
Post.first.destroy
assert_equal 0, Comment.count
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment