Skip to content

Instantly share code, notes, and snippets.

@madwork
Last active March 10, 2017 11:27
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 madwork/94bcaa528fe0ea68e510b9feda549cb4 to your computer and use it in GitHub Desktop.
Save madwork/94bcaa528fe0ea68e510b9feda549cb4 to your computer and use it in GitHub Desktop.
Self executable gist
unless File.exist?('Gemfile')
File.write('Gemfile', <<-GEMFILE)
source 'https://rubygems.org'
#gem 'rails', github: 'rails/rails'
gem 'rails', github: 'rails/rails', branch: '4-2-stable'
gem 'sqlite3'
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 :books do |t|
t.string :name
end
create_table :categories do |t|
t.string :name
end
create_table :books_categories do |t|
t.integer :book_id
t.integer :category_id
end
end
class Book < ActiveRecord::Base
has_and_belongs_to_many :categories
end
class Category < ActiveRecord::Base
has_and_belongs_to_many :books
end
class Test < Minitest::Test
def test_association_ids
book = Book.create!
category = Category.create!
book.category_ids = [category.id]
assert_equal book.category_ids, [category.id]
assert_raises(ActiveRecord::RecordNotFound) { book.category_ids += [category.id] } # ?!
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment