Created
November 25, 2013 20:48
-
-
Save pmatsinopoulos/7648629 to your computer and use it in GitHub Desktop.
Demonstrates a bug on ActiveRecord that occurs when one uses `Model.where(....).first_or_create(....)`. The `where(....)` is used also in any `Model.query` that takes place before the `first_or_create! returns. In the following test, the last assertion fails.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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' | |
# 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 :isbn, :null => false | |
t.string :name, :null => false | |
t.string :author, :null => false | |
t.integer :book_count, :null => false | |
t.timestamps | |
end | |
add_index :books, [:isbn] | |
end | |
class Book < ActiveRecord::Base | |
before_create :count_books | |
protected | |
def count_books | |
self.book_count = Book.count | |
logger.info "Number of Books: #{Book.count}" | |
logger.info "Books where isbn equals x, sql is: #{Book.where(:isbn => 'x').to_sql}" | |
end | |
end | |
class BugTest < MiniTest::Unit::TestCase | |
def test_scope_query_while_on_first_or_create | |
book = nil | |
number_of_books_before = Book.count | |
book = Book.create!(:isbn => '1', :name => 'name1', :author => 'author1') | |
number_of_books_after = Book.count | |
assert_equal 1, number_of_books_after | |
assert_equal 0, book.book_count | |
book = Book.create!(:isbn => '2', :name => 'name2', :author => 'author2') | |
number_of_books_after = Book.count | |
assert_equal 2, number_of_books_after | |
assert_equal 1, book.book_count | |
book = Book.create!(:isbn => '3', :name => 'name3', :author => 'author3') | |
number_of_books_after = Book.count | |
assert_equal 3, number_of_books_after | |
assert_equal 2, book.book_count | |
book = Book.where(:isbn => ' 4').first_or_create!( | |
:name => 'name4', | |
:author => 'author3' | |
) | |
number_of_books_after = Book.count | |
assert_equal 4, number_of_books_after | |
assert_equal 3, book.book_count | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment