Skip to content

Instantly share code, notes, and snippets.

@milk1000cc
Created April 25, 2014 23:55
Show Gist options
  • Save milk1000cc/11307343 to your computer and use it in GitHub Desktop.
Save milk1000cc/11307343 to your computer and use it in GitHub Desktop.
unless File.exist?('Gemfile')
File.write('Gemfile', <<-GEMFILE)
source 'https://rubygems.org'
gem 'rails', github: 'rails/rails'
gem 'sqlite3'
GEMFILE
system 'bundle'
end
require 'bundler'
Bundler.setup(:default)
require 'active_record'
require 'minitest/autorun'
require 'logger'
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table :articles
create_table :taggings do |t|
t.belongs_to :article
t.belongs_to :tag
end
create_table :tags
create_table :article_categories do |t|
t.belongs_to :article
t.belongs_to :category
end
create_table :categories
end
class Article < ActiveRecord::Base
has_many :taggings
has_many :tags, through: :taggings
has_many :article_categories
has_many :categories, through: :article_categories
end
class Tagging < ActiveRecord::Base
belongs_to :article
belongs_to :tag
after_create do
article.reload
puts article.tags.count
end
end
class Tag < ActiveRecord::Base
has_many :taggings
has_many :articles, through: :taggings
end
class ArticleCategory < ActiveRecord::Base
belongs_to :article
belongs_to :category
end
class Category < ActiveRecord::Base
has_many :article_categories
has_many :articles, through: :article_categories
end
class BugTest < Minitest::Test
def test_create_with_has_many_through_association
tag = Tag.create
category = Category.create
article = Article.create(tags: [tag], categories: [category])
p ArticleCategory.count # => 0
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment