Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save elfassy/98bf3b432253003ba64df853397d9b2b to your computer and use it in GitHub Desktop.
Save elfassy/98bf3b432253003ba64df853397d9b2b to your computer and use it in GitHub Desktop.
begin
require 'bundler/inline'
rescue LoadError => e
$stderr.puts 'Bundler version 1.10 or later is required. Please update your Bundler'
raise e
end
gemfile(true) do
source 'https://rubygems.org'
gem 'activerecord', '4.2.0'
gem 'sqlite3'
end
require 'active_record'
require 'minitest/autorun'
require 'logger'
Minitest::Test = MiniTest::Unit::TestCase unless defined?(Minitest::Test)
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table "categories" do |t|
t.string "name"
end
create_table "product_categories" do |t|
t.integer "product_id"
t.integer "category_id"
end
create_table "products" do |t|
t.string "name"
end
end
class Product < ActiveRecord::Base
has_many :product_categories, foreign_key: 'product_id' # remove foreign_key and it works
has_many :categories, through: :product_categories
end
class ProductCategory < ActiveRecord::Base
belongs_to :product
belongs_to :category
validates :product, :category, presence: true
end
class Category < ActiveRecord::Base
has_many :product_categories
has_many :products, through: :product_categories
end
class BugTest < Minitest::Test
def test_association_stuff
c = Category.new(name: 'Electronic')
assert c.save, c.errors.full_messages
p = Product.new(name: 'Smartphone', categories: [c])
assert p.save, p.errors.full_messages #=> ["Product categories is invalid"]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment