Skip to content

Instantly share code, notes, and snippets.

@tobypinder
Last active August 29, 2015 14:24
Show Gist options
  • Save tobypinder/929c5afbedd76b170bfb to your computer and use it in GitHub Desktop.
Save tobypinder/929c5afbedd76b170bfb to your computer and use it in GitHub Desktop.
Creating Records via #new on an AR::Relation object can fail due to enums.
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 'rails', '4.2.3' # github: 'rails/rails'
# gem 'arel', github: 'rails/arel'
gem 'sqlite3'
end
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 :things, force: true do |t|
t.integer :enum_field
end
end
class Thing < ActiveRecord::Base
enum enum_field: {
foo: 1,
bar: 2,
baz: 3
}
end
class BugTest < Minitest::Test
def test_creating_new_record_from_existing_relation
Thing.all.new # OK
Thing.all.where(enum_field: 2).new # OK
end
def test_creating_new_record_from_existing_relation_with_single_element_in_array
Thing.all.where(enum_field: [1]).new # OK, since it gets coerced into the same as `enum_field: 1`
end
def test_creating_new_record_from_existing_relation_with_multiple_elements_in_array
Thing.all.where(enum_field: [1, 2]).new # FAIL, despite being the valid way to craft IN() statements
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment